3

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

1 Answer 1

4

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());
        },
        // ...
    ]
);
Sign up to request clarification or add additional context in comments.

2 Comments

can I do this with attributes too?
Yes, with anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.