Symfony2 entity field type alternatives to "property" or "__toString()"?
Posted
by
Polmonino
on Stack Overflow
See other posts from Stack Overflow
or by Polmonino
Published on 2012-03-28T21:32:17Z
Indexed on
2012/03/28
23:29 UTC
Read the original article
Hit count: 230
Using Symfony2 entity field type one should specify property
option:
$builder->add('customers', 'entity', array(
'multiple' => true,
'class' => 'AcmeHelloBundle:Customer',
'property' => 'first',
));
But sometimes this is not sufficient: think about two customers with the same name, so display the email (unique) would be mandatory.
Another possibility is to implement __toString()
into the model:
class Customer
{
public $first, $last, $email;
public function __toString()
{
return sprintf('%s %s (%s)', $this->first, $this->last, $this->email);
}
}
The disadvances of the latter is that you are forced to display the entity the same way in all your forms.
Is there any other way to make this more flexible? I mean something like a callback function:
$builder->add('customers', 'entity', array(
'multiple' => true,
'class' => 'AcmeHelloBundle:Customer',
'property' => function($data) {
return sprintf('%s %s (%s)', $data->first, $data->last, $data->email);
},
));
© Stack Overflow or respective owner