2

我需要在我的表单中创建复选框数组。据我了解,我必须使用(type => 'Repeatable')字段。我在表单类中创建了字段:

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

我在构造函数中传递了角色 ID:

 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 }

  ]
 );

并尝试在模板中呈现此字段

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

但我只有:

 <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>

我应该怎么做才能获得三个名为“5”、“6”、“7”的复选框?我在 H::FH 的文档中找不到答案。即使在似乎包含 示例的页面上

4

1 回答 1

2

我认为问题在于构造函数的参数不直接映射到“has_field”,而只是映射到“has”。所以我需要将我的用户角色传递给一些中间变量

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

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

然后在表单类中初始化我的字段:

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

TT:

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

构造函数:

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

结果:

 <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>
于 2012-12-21T10:42:31.320 回答