I'm using building a form type that uses a form field subscriber to render some of the form fields.
The subscriber returns form options for a given field. One of the options is "choices":
$formOptions = [
...
'choices' => $choices,
];
$choices
are entities.
Consequently, they will be rendered in a form by means of __toString()
of the objects.
The __toString()
method would look something like:
public function __toString()
{
return $this->getName();
}
However, I want the "choices" representation to be $name . $id
(name concatenated with the object ID).
At the same time, I do not want to modify the object's __toString()
method since I want a different string representation only in this one form field, and not all over the system.
What options do I have?
Do I have any granular control on how Symofny form fields display passed choices?
You can use the property option according to entity field documentation 2.6
$builder->add('users', 'entity', array(
'class' => 'AcmeHelloBundle:User',
'property' => 'customToString',
));
Just make sure that the property name matches the method name
/**
* @return string
* Here you print the attributes you need
*/
public function customToString()
{
return sprintf(
'%s,
$this->$name . $this->$id,
);
}