问题描述
使用 Symfony2 实体字段类型 应该指定 属性
选项:
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.
另一种可能是在模型中实现__toString()
:
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);
},
));
推荐答案
我发现这真的很有帮助,我用你的代码找到了一个非常简单的方法,所以这里是解决方案
I found this really helpful, and I wound a really easy way to do this with your code so here is the solution
$builder->add('customers', 'entity', array(
'multiple' => true,
'class' => 'AcmeHelloBundle:Customer',
'property' => 'label',
));
在类 Customer(实体)中
And in the class Customer (the Entity)
public function getLabel()
{
return $this->lastname .', '. $this->firstname .' ('. $this->email .')';
}
呃瞧:D 该属性从实体而不是数据库中获取其字符串.
eh voila :D the property get its String from the Entity not the Database.
这篇关于Symfony2 实体字段类型替代“属性"还是“__toString()"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!