narse has asked for the wisdom of the Perl Monks concerning the following question:

I am having a problem using hidden() to generate hidden fields in forms. Here is a swatch of code to demonstrate my problem:
#!/usr/bin/perl use warnings; use strict; use CGI qw/ :standard /; print hidden( -name => "foo", -default => "bar", ), "\n";
When I run this code with the `foo' parameter defined, I get bad results. For example:
> ./hidden.pl # the code above <input type="hidden" name="foo" value="bar" /> > ./hidden.pl foo=123 <input type="hidden" name="foo" value="123" />
The value of the hidden input changes based on the pre-existing values. I see that one can use hidden() to retrieve values but I simply want to define a new one at this point. The `hidden ( $name, $value )' usage functions in the same way.

Perldoc says:
Note, that just like all the other form elements, the value of a hidden field is "sticky". If you want to replace a hidden field with some other values after the script has been called once youll have to do it manually: $query->param(hidden_name,new,values,here);
Destroying CGI parameters in order to insert hidden fields does not seem reasonable to me. There must be a bettery way. Is there a way to overcome this problem simply? And is there some reasoning behind the way things currently are?

Thanks in advance.

Replies are listed 'Best First'.
Re: Hidden fields using CGI
by eric256 (Parson) on Apr 12, 2004 at 16:45 UTC

    You can use the -override parameter to force it to use the default value.

    use strict; use warnings; use CGI qw/ :standard /; print hidden( -name => "foo", -default => "bar", ), "\n"; print hidden(-name => "baz", -default => "bab" , -override => 1), "\n" +; __DATA__ C:\test>perl cgi.pl foo=test baz=test <input type="hidden" name="foo" value="test" /> <input type="hidden" name="baz" value="bab" /> C:\test>perl cgi.pl <input type="hidden" name="foo" value="bar" /> <input type="hidden" name="baz" value="bab" />

    ___________
    Eric Hodges
      Ah, that does the trick, thank you. Now that I know the keyword, I see it all over the documentation.
Re: Hidden fields using CGI
by Ovid (Cardinal) on Apr 12, 2004 at 16:48 UTC

    If I understand you correctly, you want to add to the hidden fields rather than overwrite them. In that case, why not add the original values back to the parameter?

    $query->param($hidden_name, $query->param($hidden_name), @plus_the_new_values );

    Cheers,
    Ovid

    New address of my CGI Course.