简体   繁体   中英

HTML::FormHandler dynamically set default form value

I'm using HTML::FormHandler and I'd like to be able to dynamically set default values for the form. Here would be a good example of what I would like to be able to do:

#this doesn't work
my $form = myapp::Form::Example->new(field1=>'default1',field2=>$default2);

In the example above, field1 's value would hold "default1" and field2 's value would hold whatever the scalar $default2 holds. However, the above example does not do this. Does anyone know of a way to do this? Thanks!

There are a lot of ways of setting default values. You can use an init_object:

my $form = MyApp::Form::Example->new;
$form->process( init_object => { field1 => 'default1', field2 => 'default2' }, ... );

You can also use the 'defaults' shortcut for updating fields dynamically:

$form->process( defaults => { field1 => 'default1', field2 => 'default2' }, ... );

The 'init_object' acts instead of a database row (item), so if you're also passing an 'item', you might also have to set the 'use_init_obj_over_item' flag. It uses the object/form 'value' format, which includes nested hashrefs and arrayrefs. The 'defaults' hashref requires a flattened hashref, such as you get from the 'fif' (fill-in-form) method.

See https://metacpan.org/module/HTML::FormHandler::Manual::Defaults

From the docs the code in the Q is good. Please try to debug thhe problem with the following. This will allow you peeek "inside" the object and see whats going on.

My guess: The default value gets overwritten with actual data or variable is empty.

use Data::Dumper;
print Dumper($default2);
my $form = myapp::Form::Example->new(field1=>'default1',field2=>$default2);
print Dumper($form);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM