Symfony change ChoiceType multiple expanded input name

2k Views Asked by At

Having Location as:

id    name        title
---   -----       ------
1     usa         United States of America
2     uk          United Kingdom
3     canada      Canada

I have an ** EntityType** form field, named location:

class OrderType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('location', EntityType::class, array(
            'class'        => Location::class,
            'choice_label' => 'title',
            'choice_name'  => 'name',
            'choice_value' => 'id',
            'multiple'     => true,
            'expanded'     => true,
            'data'         => array(
                'usa', 'canada'
            ),
        ));
    }
}

and I want to have, for example, some checkboxes (EntityType, multiple=true, expanded=true) checked (using data option).

I set choice_name option to location's name, but the name form field attribute does not change.

HTML

<input type="checkbox" id="order_location_usa" name="order[location][]" value="1">
<input type="checkbox" id="order_location_uk" name="order[location][]" value="2">
<input type="checkbox" id="order_location_canada" name="order[location][]" value="3">

What am I missing?

1

There are 1 best solutions below

0
On

If you can pass in an entity, you could do this:

'choice_name' => function($location){
    return $location->getName();
}

Otherwise, 'name' is not defined and that's why it is blank. Documentation is here: https://symfony.com/doc/current/reference/forms/types/entity.html#choice-name

So choice_name is callable (a function).