【问题标题】:Symfony2 - How to display data in a form rowSymfony2 - 如何在表单行中显示数据
【发布时间】:2016-08-17 15:58:47
【问题描述】:

我想为选择字段类型显示的不仅仅是标签和小部件。

假设我有一个 stdclass 对象数组:

这是我的控制器代码

$foo = new stdClass();
$foo->icon = 'fooicon.gif';
$foo->name = 'foo';

$bar = new stdClass();
$bar->icon = 'baricon.gif';
$bar->name = 'bar';    

$formdata->choices = array($foo, $bar);

$form = $this->createForm(new CustomForm(), $formdata);

这是我的表单类型

// FormType
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add() // Some other fields, not useful

    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
        $data = $event->getData();
        $form = $event->getForm();

        // There are some checks here ... let's summarize them by using true
        if (true) {
            $form->add('myChoices', 'choice', array(
                'choices' => $data->choices,
                'choice_label' => 'name',
                'choices_as_values' => true,
                'multiple' => true,
                'expanded' => true,
            ));
        }
    });
}
?>

template.html.twig

    {% if form.myChoices is defined %}
         {{ form_row(form.myChoices) }}
    {% endif %}

有了这个,我对每个选项都有一个复选框,名称为标签。我想要实现的是显示每个复选框的图标和名称。 我该怎么做?

我正在使用 symfony 2.7

【问题讨论】:

标签: symfony symfony-forms symfony-2.7


【解决方案1】:

在 Twig 中,您可以使用 for 循环来获取带有标签的多个值。

喜欢下面的代码:

{% for myChoices in form.myChoices %}
    <label class="check">
        {{ form_errors(myChoices) }}
        {{ form_widget(myChoices) }}
        <span>{{ myChoices.vars.label }}</span>
    </label>
{% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多