加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

表单 – Symfony2实体字段类型替代“属性”或“__toString()”?

发布时间:2020-12-14 21:48:11 所属栏目:资源 来源:网络整理
导读:使用Symfony2 entity field type应该指定属性选项: $builder-add('customers','entity',array( 'multiple' = true,'class' = 'AcmeHelloBundle:Customer','property' = 'first',)); 但有时这还不够:考虑两个同名的客户,所以显示电子邮件(唯一)将是强制性
使用Symfony2 entity field type应该指定属性选项:
$builder->add('customers','entity',array(
    '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,$this->email);
    }
}

后者的不利之处在于,您被迫以所有形式的方式显示实体。

有什么其他方法可以使这个更灵活吗?我的意思是回调函数:

$builder->add('customers','property' => function($data) {
         return sprintf('%s %s (%s)',$data->first,$data->last,$data->email);
     },));

解决方法

我发现这真的很有帮助,我用一个很简单的方法来解决你的代码,所以这里是解决方案
$builder->add('customers',array(
'multiple' => true,'property' => 'label',));

而在班级客户(实体)

public function getLabel()
{
    return $this->lastname .','. $this->firstname .' ('. $this->email .')';
}

eh voila:D属性从实体获取其字符串而不是数据库。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读