Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony Form EntityType, add custom data to choice

I have a form with a field of type 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();
                },
            ]
        );

As you can see, the form displays checkbox with the label Contact->getName().

Every thing goes right, the form display each checkbox like:

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

Now for each checkbox I would like to add extra data like the email address. I want the checkbox to be displayed like this:

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

How can I pass the email data to the template (the twig block)?

like image 947
wonzbak Avatar asked Dec 07 '25 07:12

wonzbak


1 Answers

See the documentation for choice_label: http://symfony.com/doc/current/reference/forms/types/entity.html#choice-label

Your amended code would like something like:

$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());
        },
        // ...
    ]
);
like image 179
Jonny Avatar answered Dec 08 '25 23:12

Jonny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!