I want a simple checkbox (with just one option, either it's checked, or
not). I want the form to see whether I checked it, of course, and just re-display
it in the same state when submitted.
#!/usr/bin/perl
use CGI::FormBuilder;
use CGI;
my $q=CGI->new;
print $q->header;
my $form=CGI::FormBuilder->new(sticky => 1, fields => ["testing"]);
print "got: ".$form->field("testing")."\n";
$form->field(
name => "testing",
type => "checkbox",
value => 1,
cgi => $q,
options => [ [ 1 => "checked?" ] ],
);
print $form->render;
If you try this code out, the checkbox will initially be checked, and it will say
"got:" above it. Leave it checked and post the form, and it stays checked, and it
shows "got: 1". As expected so far.
Now, uncheck it, and post the form. Here CGI::FormBuilder loses track of the checkbox
not being checked, and becomes checked again. This despite sticky mode being enabled.
This doesn't happen for other types of fields. So if it's converted to radio
buttons, it will remember if 0 or 1 was chosen, stickily:
#!/usr/bin/perl
use CGI::FormBuilder;
use CGI;
my $q=CGI->new;
print $q->header;
my $form=CGI::FormBuilder->new(sticky => 1, fields => ["testing"]);
print "got: ".$form->field("testing")."\n";
$form->field(
name => "testing",
type => "radio",
value => 1,
cgi => $q,
options => [ 0, 1 ],
);
print $form->render;
But, that's not as usable as a checkbox, IMHO.
To work around this problem, you have to avoid setting a value for the checkbox
when the form is submitted:
#!/usr/bin/perl
use CGI::FormBuilder;
use CGI;
my $q=CGI->new;
print $q->header;
my $form=CGI::FormBuilder->new();
$form->field(
name => "testing",
type => "checkbox",
cgi => $q,
options => [ [ 1 => "checked?" ] ],
);
print "got: ".$form->field("testing")."\n";
if (! $form->submitted) {
$form->field(name => "testing", value => 1);
}
print $form->render;
Works ok, but is not very consistent with the rest of formbuilder's behavior
WRT sticky fields, and was not easy for me to come up with..