简体   繁体   中英

Symfony Custom Form Select Value

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');
            }
        ));

As Symfony Doc says choice_label can be also a callable which gives you two options.

  1. 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

  1. 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(); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM