简体   繁体   中英

How to create multiple fields in HTML::FormHandler

I need to create array of checkboxes in my form. As I understand I have to use (type => 'Repeatable') field. I've created fields in the form class:

has_field 'userroles'       => ( type => 'Repeatable');
has_field 'userroles.idx'   => ( type => 'Checkbox');  

I've passed role ids in constructor:

 my $form = MyApp::Form::adduser->new( 
  ml_labels         => $c->stash->{labels},
  userlang          => $c->stash->{userlang}, 
  langs_available   => [map{+{value => $_->id, label => $_->id}}@all_langs],
  userroles => [
   { idx => 5 },
   { idx => 6 },
   { idx => 7 }

  ]
 );

and try to render this fields in template

 <div style="float:left">
  [% form.field('userroles').render %]
 </div>

but I got only:

 <div style="float:left">
  <div class="hfh-repinst">
  <div>
 <label for="userroles.0.idx">Idx</label>
 <label class="checkbox" for="userroles.0.idx"><input type="checkbox" name="userroles.0.idx" id="userroles.0.idx" value="1" />

 </label>
 </div>

What should I do to get three checkboxes with names '5','6','7'? I can't find the answer in the documentation to H::FH. Even on the page that seems to contain example

I think the problem is that parameters from constructor do not map directly to "has_field" but only to "has". So I need to pass my userroles to some intermediate variable

 has 'userroles'            => ( is => 'rw' );

 has_field 'roles'          => ( type => 'Repeatable');
 has_field 'roles.idx'      => ( type => 'Text');
 has_field 'roles.value'    => ( type => 'Text');

and then initialize my field in form class:

 sub init_object{
   my $self = shift;
   my $roles = [];
   foreach my $role (@{$self->userroles}){
     push(@$roles, $role);
   }
   return { roles => $roles }
 }

TT:

 [% form.field('roles').render %]

constructor:

    ...
 userroles => [
+{ idx => 5, value => 15 },
+{ idx => 6, value => 15 },
+{ idx => 7, value => 15 }
 ]
   ...

result:

 <div class="hfh-repinst">
  <div>
   <label for="roles.0.idx">Idx</label>
   <input type="text" name="roles.0.idx" id="roles.0.idx" value="5" />
  </div>
  <div>
   <label for="roles.0.value">Value</label>
   <input type="text" name="roles.0.value" id="roles.0.value" value="15" />
  </div>
 </div>
<div class="hfh-repinst">
 <div>
  <label for="roles.1.idx">Idx</label>
  <input type="text" name="roles.1.idx" id="roles.1.idx" value="6" />
 </div>
 <div>
  <label for="roles.1.value">Value</label>
  <input type="text" name="roles.1.value" id="roles.1.value" value="15" />
 </div>
</div>

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