Reputation: 2824
I am using Symfony3 and I want to be able to display custom select values by combining two fields together such as name and city. So, in essence in the select box it would show this:
------------------------------------
John Smith - Denver
------------------------------------
Abe Lincoln - Washington D.C
------------------------------------
George Washington - Washington D.C
------------------------------------
etc...
------------------------------------
Here's my form...
$builder->add('person', EntityType::class, array(
'required'=>false,
'class'=>'AppBundle:Person',
'choice_label'=>'name',
'label'=>'Choose the person',
'empty_data'=>null,
'placeholder'=>"None",
'query_builder' => function(EntityRepository $repository) {
return $repository->createQueryBuilder('p');
}
));
Upvotes: 0
Views: 106
Reputation: 15656
As Symfony Doc says choice_label
can be also a callable which gives you two options.
Create a getter for composed value that should represent entity like:
class Person {
// ...
public function getComposedName() {
return $this->name . ' - ' . $this->city;
}
}
And then in the form set choice_label
to 'composedName'
.
Please note that it's composedName
, and not getComposedName
, because Symfony will use PropertyAccesor
here, it will try also getting value with a getter getComposedName
.
This may be useful if you'll need this value in other places
If you need this only in this particular form, then you can pass an anonymous function directly to the form:
'choice_label'=> function($person) {
return $person->getName(). ' - ' . $person->getCity();
}
Upvotes: 1