Your trainer will now demonstrate and discuss how you can use what you've just learnt to create a multi-form "wizard" interface, where values are remembered from one form to the next and passed using hidden fields.
<INPUT TYPE="HIDDEN" VALUE="..." NAME="..."> |
Source code for this example is available in your cgi-bin directory as wizard.cgi.
First, we print some headers and pick up the "step" parameter to see what step of the wizard interface we're up to. We have four subroutines, named step1 through step4, which do the actual work for each step.
#!/usr/bin/perl -w use strict; use CGI 'param'; print <<"END"; Content-type: text/html <html> <body> <h1>Wizard interface</h1> END my $step = param('step') || 0; step1() unless $step; step2() if $step == 2; step3() if $step == 3; step4() if $step == 4; print <<"END"; </body> </html> END |
Here are the subroutines. The first one is fairly straightforward, just printing out a form:
# # Step 1 -- Name # sub step1 { print qq( <h2>Step 1: Name</h2> <p> What is your name? </p> <form method="POST" action="wizard.cgi"> <input type="hidden" name="step" value="2"> <input type="text" name="name"> <input type="submit"> </form> ); } |
Steps 2 through 4 require us to pick up the CGI parameters for each field that's been filled in so far, and print them out again as hidden fields:
# # Step 2 -- Quest # sub step2 { my $name = param('name'); print qq( <h2>Step 2: Quest</h2> <p> What is your quest? </p> <form method="POST" action="wizard.cgi"> <input type="hidden" name="step" value="3"> <input type="hidden" name="name" value="$name"> <input type="text" name="quest"> <input type="submit"> </form> ); } # # Step 3 -- favourite colour # sub step3 { my $name = param('name'); my $quest = param('quest'); print qq( <h2>Step 3: Silly Question</h2> <p> What is the airspeed velocity of an unladen swallow? </p> <form method="POST" action="wizard.cgi"> <input type="hidden" name="step" value="4"> <input type="hidden" name="name" value="$name"> <input type="hidden" name="quest" value="$quest"> <input type="text" name="swallow"> <input type="submit"> </form> ); } |
Step 4 simply prints out the values that the user entered in the previous steps:
# # Step 4 -- finish up # sub step4 { my $name = param('name'); my $quest = param('quest'); my $swallow = param('swallow'); print qq( <h2>Step 4: Done!</h2> <p> Thank you! </p> <p> Your name is $name. Your quest is $quest. The airspeed velocity of an unladen swallow is $swallow. </p> ); } |
Add another question to the wizard.cgi script.