问题描述
使用Symfony2 ,应指定 property
选项:
$ builder-> add('customers','数组'(
'multiple'=> true,
'class'=>'AcmeHelloBundle:Customer',
'property'=>'first',
));
但有时候这还不够:想想两个同名的客户, )
另一种可能性是在模型中实现 __ toString()
:
class Customer
{
public $ first,$ last,$ email;
public function __toString()
{
return sprintf('%s%s(%s)',$ this-> first,$ this-> last, $这个 - >电子邮件);
$ / code>
后者的缺点是你强制在所有表单中以相同的方式显示实体。
是否有其他方法可以使它更灵活?
我的意思是像回调函数: $ builder-> add('customers' ,'实体',数组(
'multiple'=> true,
'class'=>'AcmeHelloBundle:Customer',
'property'=> function($ data) {
return sprintf('%s%s(%s)',$ data-> first,$ data-> last,$ data-> email);
},
));
我发现这真的很有帮助,简单的方法来做到这一点与您的代码,所以这里是解决方案
$ builder-> add('customers','entity ',array(
'multiple'=> true,
'class'=>'AcmeHelloBundle:Customer',
'property'=>'label',
));
并且在Customer(实体)类中
public function getLabel()
{
return $ this-> lastname。','。 $ this-> firstname。'('。$ this-> email。')';
}
eh voila:D属性从实体中获取String而不是数据库。
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);
},
));
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',
));
And in the class Customer (the Entity)
public function getLabel()
{
return $this->lastname .', '. $this->firstname .' ('. $this->email .')';
}
eh voila :D the property get its String from the Entity not the Database.
这篇关于Symfony2实体字段类型替代“属性”或“__ toString()”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!