Symfony2实体字段类型替代"property"或"__toString()"?

Pol*_*ino 18 forms symfony-forms symfony

使用Symfony2 实体字段类型应指定property选项:

$builder->add('customers', 'entity', array(
    'multiple' => true,
    'class'    => 'AcmeHelloBundle:Customer',
    'property' => 'first',
));
Run Code Online (Sandbox Code Playgroud)

但有时这还不够:想想两个同名的客户,所以显示电子邮件(唯一)是强制性的.

另一种可能性是__toString()在模型中实现:

class Customer
{
    public $first, $last, $email;

    public function __toString()
    {
        return sprintf('%s %s (%s)', $this->first, $this->last, $this->email);
    }
}
Run Code Online (Sandbox Code Playgroud)

后者的缺点是你被迫在所有形式中以相同的方式显示实体.

有没有其他方法可以使这更灵活?我的意思是像回调函数:

$builder->add('customers', 'entity', array(
    'multiple' => true,
    'class'    => 'AcmeHelloBundle:Customer',
    'property' => function($data) {
         return sprintf('%s %s (%s)', $data->first, $data->last, $data->email);
     },
));
Run Code Online (Sandbox Code Playgroud)

小智 41

我发现这非常有用,我用一个非常简单的方法来完成你的代码,所以这里是解决方案

$builder->add('customers', 'entity', array(
'multiple' => true,
'class'    => 'AcmeHelloBundle:Customer',
'property' => 'label',
));
Run Code Online (Sandbox Code Playgroud)

并在类Customer(实体)

public function getLabel()
{
    return $this->lastname .', '. $this->firstname .' ('. $this->email .')';
}
Run Code Online (Sandbox Code Playgroud)

呃瞧:D属性从实体而不是数据库中获取其字符串.

  • 您应该使用getter而不是直接访问值.`return $ this-> getLastname().','.$ this-> getFirstname().' ('.$ this-> getEmail().')';` (6认同)