如何使用querybuilder使用具有实体类型形式的转换器

时间:2016-10-18 14:34:49

标签: forms symfony transformation

以下是我创建的一些表单:

$form_roles = $this->createFormBuilder($defaultData)
   ->add('roles', 'entity', array(
         'class' => 'MyBundle:Role',
         'query_builder' => function(EntityRepository $er) {
              return $er->createQueryBuilder('r')
                  ->orderBy('r.description', 'ASC');
          },
          'choice_label' => 'description',
          'label' => 'My roles'
     ))          
  ->getForm();

Role对象中显示的description字段不足以将其显示给应用程序的用户。所以我想改变它。 当我使用我想要查看的每个属性创建querybuilder但我从未在实体类型中创建查询构建器时,我已经在AbstractType类中使用了变换器。

所以我创建了一个这样的RoleTransformer类:

class RoleTransformer implements DataTransformerInterface {
  public function transform($entity) {
   $substitution_value = null;

   switch ($entity->getDescription()) {
       case 'ROLE_INPUT':
           $substitution_value = "the value I want to see for this role";
           break;
       case 'ROLE_VALIDATION':
           $substitution_value = "the value I want to see for this role";
           break;
       case 'ROLE_ADMIN':
           $substitution_value = "the value I want to see for this role";
           break;
       default:
           $substitution_value = "the value I want to see for this role";
    }

    return $substitution_value;
  }

  public function reverseTransform($substitution_value) {
     return substitution_value; //the form is not submitted, I have no interest in reverse transformation I think.
  }
}

在我构建表单的控制器中,我添加了这个:

$ role_transformer = new RoleTransfomer()//不确定是否必须传递内容或者是否由框架完成

我添加了表单构建器(在> getForm()之前):

->addModelTransformer($role_transformer)

我以为我会将一个角色对象传递给transform方法,但它是一个数组,不幸的是它是空的。

我认为我离解决方案太远了,有人可以帮助我吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

为什么不采用这种逻辑并将其直接注入带有匿名函数的choice_label,如下所述:

http://symfony.com/doc/current/reference/forms/types/choice.html#choice-label

'choice_label' => function ($value, $key, $index) {
    switch ($value) {  // This may actually be key depending on how you have it setup
       case 'ROLE_INPUT':
           $substitution_value = "the value I want to see for this role";
           break;
       case 'ROLE_VALIDATION':
           $substitution_value = "the value I want to see for this role";
           break;
       case 'ROLE_ADMIN':
           $substitution_value = "the value I want to see for this role";
           break;
       default:
           $substitution_value = "the value I want to see for this role";
    }
    return $substitution_value;
},