【问题标题】:How to use transformer with entity type form using a querybuilder如何使用查询构建器将转换器与实体类型表单一起使用
【发布时间】:2016-10-18 14:34:49
【问题描述】:

这是我创建的一些表格:

$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();

角色对象中显示的描述字段不足以将其显示给应用程序的用户。所以我想改造它。 当我使用我想查看但从未在实体类型中查看的每个属性创建查询构建器时,我已经在 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)

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

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

谢谢。

【问题讨论】:

    标签: forms symfony transformation


    【解决方案1】:

    为什么不采用该逻辑并使用匿名函数将其直接注入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;
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 2021-09-03
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      • 1970-01-01
      相关资源
      最近更新 更多