Symfony Form EntityType,添加自定义数据到选择

Symfony Form EntityType, add custom data to choice

我有一个字段类型为 EntityType 的表单:

$builder->add(
            'contacts',
            EntityType::class,
            [
                'label'         => 'Recipient',
                'required'      => false,
                'expanded'      => true,
                'multiple'      => true,
                'class'         => 'MyApp\Entity\Contact',
                'choice_label'  => 'name',
                'query_builder' => function (EntityRepository $er)  {

                    return $er->createQueryBuilder('c')

                },
                'group_by'      => function (Contact $contact, $key, $index) {
                    return $contact->getClient()->getName();
                },
            ]
        );

如您所见,表单显示了带有标签 Contact->getName() 的复选框。

一切顺利,表单显示每个复选框如下:

<input id="id_checkbox" type="checkbox" />
<label for="id_checkbox">name</label>

现在我想为每个复选框添加额外的数据,例如电子邮件地址。我希望复选框显示如下:

<input id="id_checkbox" type="checkbox" />
<label for="id_checkbox"><span title="contact_email">contact_name</span></label>

如何将电子邮件数据传递到模板(树枝块)?

请参阅 choice_label 的文档:http://symfony.com/doc/current/reference/forms/types/entity.html#choice-label

您修改后的代码类似于:

$builder->add(
    'contacts',
    EntityType::class,
    [
        'label'         => 'Recipient',
        'required'      => false,
        'expanded'      => true,
        'multiple'      => true,
        'class'         => 'MyApp\Entity\Contact',
        'choice_label'  => function ($contact) {
            return sprintf('%s (%s)', $contact->getName(), $contact->getEmail());
        },
        // ...
    ]
);