Show multiple property values in a form select drop down in Symfony

This code snippet demonstrates how you can show multiple property values in a form select drop down in Symfony.

A symfony form builder for an entity might look something like this:

$builder
    ->add('product', 'entity', [
        'class' => 'App\MyBundle\Entity\Product',
        'property' => 'name',
        'placeholder' => 'Select',
        'choices' => $this->choices,
      ]);

This would show a list of products on a drop down with the product name being used as the drop down value. But what if you want to use multiple properties from the product entity on the drop down?

You can achieve this by adding a method on the entity itself; let's say the product has a 'price' column that you want to display with the name :

/**
* @return string
*/
public function getNameAndPrice()
{
    return $this->name  . ' - ' . $this->price;
}

You can then reference this in your form like so:

$builder
    ->add('product', 'entity', [
        'class' => 'App\MyBundle\Entity\Product',
        'property' => 'nameAndPrice',
        'placeholder' => 'Select',
        'choices' => $this->choices,
     ]);

The select drop down will now display as Product Name - Product Price.

Using toString method

An alternative to the above approach is to remove the 'property' attribute from the form array altogether and add a __toString() method to your entity like so:

    /**
* @return string
*/
public function __toString()
{
    return $this->name  . ' - ' . $this->price;
}

The second approach is more appropriate if this is how you would like the name of the entity to be referenced throughout your application.

Sign Up

NEXT: Migrate a database to a different server by command line

This article documents the steps to migrate a database from one server to another using the command line.

comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.