在Symfony / Twig的表格中包裹一堆选择

时间:2014-11-08 18:28:17

标签: php symfony twig

我希望以这种方式将同一标签下面列出的许多复选框分组:

The desired widget

我有这段代码:

$builder->add('cleanliness', 'choice', array(
    'choices'   => array('Strongly disagree', 'Disagree', 'Neither agree nor disagree', 'Agree', 'Strongly agree'),
    'multiple'  => true,
    'expanded' => true
));
$builder->add('waitingTime', 'choice', array(
    'choices'   => array('Strongly disagree', 'Disagree', 'Neither agree nor disagree', 'Agree', 'Strongly agree'),
    'multiple'  => true,
    'expanded' => true
));
... And a bunch of other checkboxes piles

1 个答案:

答案 0 :(得分:1)

在控制器中:

$answers = array('Strongly disagree', 'Disagree', 'Neither agree nor disagree', 'Agree', 'Strongly agree');

// ...

$builder->add('cleanliness', 'choice', array(
    'label' => 'The clinic is clean',
    'multiple' => true,
    'expanded' => true,
    'choices' => $answers
));
$builder->add('waitingTime', 'choice', array(
    'label' => 'My waiting time was reasonable',
    'multiple' => true,
    'expanded' => true,
    'choices' => $answers
));

// ...

return array('form' => $form->createView(), 'answers' => $answers);

然后在视图中......

<table border="1">
  <tr>
    <td></td>
  {% for answer in answers %}
    <td>{{ answer }}</td>
  {% endfor %}
  </tr>
  <tr>
  <td>{{ form_label(form.waitingTime) }}</td>
  {% for choice in form.waitingTime %}
    <td>{{ form_widget(choice) }}</td>
  {% endfor %} 
  </tr>
  <tr>
  <td>{{ form_label(form.cleanliness) }}</td>
  {% for choice in form.cleanliness %}
    <td>{{ form_widget(choice) }}</td>
  {% endfor %} 
  </tr>
  {# and so on... #}
</table>

无论如何,这是一般的要点。这些选择真的应该是复选框,还是单选按钮,这样他们只能选择其中一个?如果是这样,请将expand扩展设置为true,将multiple设置为false。