我正在使用构建一个表单类型,该类型使用表单字段订阅者来呈现一些表单字段。
订阅者返回给定字段的表单选项。其中一个选项是"选择":
$formOptions = [
...
'choices' => $choices,
];
CCD_ 1是实体
因此,它们将通过对象的__toString()
以某种形式呈现。
__toString()
方法看起来像:
public function __toString()
{
return $this->getName();
}
但是,我希望"选项"表示为$name . $id
(名称与对象ID连接)
同时,我不想修改对象的__toString()
方法,因为我只想在这一个表单字段中使用不同的字符串表示,而不是在整个系统中使用。
我有什么选择
我对Symofny表单字段如何显示传递的选择有任何精细控制吗?
由于Symfony 2.7,您可以使用带有回调的choice_label
选项来动态创建您选择的标签:
$builder->add('name', 'choice', array(
'choices' => ...,
'choice_label' => function ($choice) {
return $choice->name.$choice->id;
},
));
本例假设您的选择是具有公共$id
和$name
属性的对象。
你可以试试这样的东西吗?:
$formChoices = [];
foreach ($choices as $key => $entity) {
$formChoices[$entity->getId()] = sprintf('%s %s', $entity->getName(), $entity->getId());
}
$formOptions = [
...
'choices' => $formChoices,
];
您可以根据实体字段文档2.6 使用属性选项
$builder->add('users', 'entity', array(
'class' => 'AcmeHelloBundle:User',
'property' => 'customToString',
));
只需确保属性名称与方法名称匹配即可
/**
* @return string
* Here you print the attributes you need
*/
public function customToString()
{
return sprintf(
'%s,
$this->$name . $this->$id,
);
}