in reply to Keeping Form Values

Greetings all,
I do an aweful lot of CGI scripting and have run into this very problem. I would suggest relegating the mail form to a sub within your processing script then you can prepopulate it programatically.
Here is a prepopulation script I wrote early on.
pass it a string containing your form and a reference to a hash containing your data keyed by the values you would find in the corresponding form.
it will return you a string contianing your form prepopulated.
I am positive this can be rewritten more efficiently but I hope this helps.
sub prepopulate_form{ my ($frm_str, $hashref) = @_; my %values = %$hashref; my @val_keys = keys(%values); for(my $i=0;$i<(scalar(@val_keys));$i++){ my $name = $val_keys[$i]; my $frm_elm; if( $frm_str =~ m/(<(input|textarea)[^>]*name="$name"[^>]*>)/) +{ $frm_elm = $1; }elsif( $frm_str =~ m%(<select name="$name".*?/select>)%s ){ $frm_elm = $1; } my $new_elm = $frm_elm; if($frm_elm =~ m/<input/){ my $type = $1 if($frm_elm =~ m/type="([^"]*)"/); my $value = $1 if($frm_elm =~ m/value="([^"]*)"/); if($type eq "radio"){ $frm_elm = $1 if($frm_str =~ /(<input[^>]*name="$name" +[^>]*value="$values{$name}"[^>]*>)/); $new_elm = $frm_elm; $new_elm =~ s/>/ checked="true">/; }elsif($type eq "checkbox"){ if($values{$name} == 1){ $new_elm =~ s/>/ checked>/; } }elsif($type =~ m/text/){ if($new_elm =~ /value=/){ $new_elm =~ s/value="[^"]*"/value="$values{$name}" +/; }else{ $new_elm =~ s/>/ value="$values{$name}">/; } } }elsif($frm_elm =~ /<textarea/){ $new_elm =~ s/(<textarea[^>]*>)/$1 $values{$name}/; }elsif($frm_elm =~ /<select/){ $new_elm =~ s/(value="$values{$name}")/$1 selected/s; } $frm_elm =~ s/([\-\?\)\(\/])/\\$1/g; $frm_str =~ s/$frm_elm/$new_elm/s; } return $frm_str; }#end prepopulate_form sub

Replies are listed 'Best First'.
Re: Re: Keeping Form Values
by cees (Curate) on Oct 22, 2003 at 05:38 UTC

    If you need something like this in the future, have a look at HTML::FillInForm which does the exact same thing, except it uses HTML::Parser instead of a load of regexps.

    Whenever I come up with a cool new idea for a module, I find out someone has already put it up on CPAN.