next up previous contents
Next: User Information methods Up: Perl on the Web Previous: HTML Helper methods in   Contents


Combo Forms

Most programmers who use perl to produce pages with form elements write CGI scripts which are sometimes known as combo forms. In a combo form, the same CGI script produces the empty form to be filled out, and processes it once the user clicks the submit button of the form. This eliminates the headaches of trying to keep a static HTML page containing a form in synch with your perl script, and provides some of the conveniences of languages which embed their instructions inside of HTML, like PHP and ASP. Using the CGI module, it's easy to tell whether or not a script is called from a browser form, or if it was called directly through a URL; when the script is called from a form, the param method, called with no arguments, will return an array containing the names of all the CGI variables defined through the form which was invoked; if there was no form, then the param method will return undef. Thus, if the param method returns a true value, it indicates that the CGI script was called from a form, while if it returns false, then the script was called through a URL entered in a browser or from a link, and it needs to generate the necessary form.

The following trivial example either creates a form with a textfield for a name (when called directly), or prints the name it received if called through a form.

      use CGI;
      $q = new CGI();

      if(not defined $q->param()){   # called directly
          print $q->header(),$q->start_html("Simple Form");
          print $q->h1("Simple Form"),$q->br();
          print $q->startform(-action=>$q->self_url());
          print "Enter your name: ",$q->textfield(-name=>'who');
	  print "<br>",$q->submit(-label=>'Enter');
          print $q->endform(),$q->end_html();
       }
      else{                          # called from a form
          print $q->header(),$q->start_html("Form Response");
          print $q->h1("Form Response");
          $who = $q->param('who');
          print "Welcome to the web, $who",$q->end_html();
      }
Note the use of the self_url method, which is particularly useful with combo forms.


next up previous contents
Next: User Information methods Up: Perl on the Web Previous: HTML Helper methods in   Contents
Phil Spector 2002-10-18