Basic Tutorial - Step 2: A Simple Form Back
<< Intro to FormBuilder | Form Method >>A simple FormBuilder application looks like the following:
#!/usr/bin/perl
use CGI::FormBuilder;
@fields = qw(first_name last_name email phone);
$form = CGI::FormBuilder->new(
fields => \@fields,
);
if ($form->submitted && $form->validate) {
# you would write code here to act on the form data
$fname = $form->field('first_name');
$lname = $form->field('last_name');
print $form->confirm(header => 1);
} else {
print $form->render(header => 1);
}
First, we define our fields, and create a new $form
object specifying those fields (we have to backslash our \@fields
array so that it's passed in one piece). FormBuilder then takes them, creates
human-readable labels for each field, and lays everything out in an
HTML table automatically via the $form->render method.
In fact, FormBuilder even titles the name of the form based on the
name of the script! (personal_info.pl becomes "Personal Info").
When the user hits the "Submit" button, $form->submitted
will return true, which in our example above would also cause
$form->validate to execute (due to the && in
the if statement). If both return true, it means valid form data
was submitted, and you can then do whatever you need to do with that data.
Getting to the form data is as easy as using the field()
method in a way similar to CGI.pm's param()
function. The field() function has numerous other
uses too, as we will see later.
Stop for a second and see this in action. Then, check out the HTML generated by this application before going on to the next step.