Symfony 2创建具有2个属性的实体表单字段 [英] Symfony 2 Create a entity form field with 2 properties

查看:76
本文介绍了Symfony 2创建具有2个属性的实体表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 symfony2 ,并且有一种形式可以将一个用户的关系保存到某些规则中.这些规则由公司的管理员用户设置.在这种形式下,我选择了要更新的用户后,必须选择该用户具有权限的规则.

I am using symfony2 and have a form to save the relation of one user to some rules. These rules are setted by the admin user of the company. In this form, after I selected a user to update, I have to select wich rule this user have permission.

问题是我可能有多个规则具有相同的名称(这是另一个实体),但是值不同.因此,当我构建选择框时,必须显示名称和值,如:

The problem is that I may have more then one rule with the same name (it's another entity) but the values are different. So, when I build the selectbox I must show the name and the value like:

  1. 数量-10
  2. 数量-20
  3. 商品价值-200
  4. 商品价值-500

但是现在我只需要使用下面的代码就可以显示-$ value":

But now I just can show without the "- $value" using the code bellow:

$form = $this->createFormBuilder()->add('myinput', 'entity', array(
                    'class' => 'myBundle:Rule',
                    'property' => 'childEntity.name',
                    'label' => 'Filas Permitidas',
                    'expanded' => false,
                    'multiple' => true,
                    'choices' => $this->getDoctrine()
                            ->getRepository('MyBundle:Rule')
                            ->findAll(),
                    'required' => true,
                ))->getForm();

因此,作为属性,我想获取$myEntity->getChildEntity()->getName()$myEntity->getValue().

So, as property I wanted to get $myEntity->getChildEntity()->getName() and the $myEntity->getValue().

有什么方法可以做到这一点?

Is there some way to do this?

推荐答案

是的,在实体类中定义一个getUniqueName()方法,例如:

Yes, define a getUniqueName() method in the entity class like:

public function getUniqueName()
{
    return sprintf('%s - %s', $this->name, $this->value);
}

并编辑property表单选项:

'property' => 'childEntity.uniqueName',

您也可以省略property选项并以相同的方式定义__toString()方法,以便不以每种形式重复property选项的设置.

You also can omit the property option and define the __toString() method same way in order to not repeat the setting of the property option in every form.

这篇关于Symfony 2创建具有2个属性的实体表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆