表单类型中的自定义Query_builder函数

时间:2014-03-29 18:00:25

标签: symfony doctrine-orm

来自docs:

use Doctrine\ORM\EntityRepository;
// ...

$builder->add('users', 'entity', array(
    'class' => 'AcmeHelloBundle:User',
    'query_builder' => function(EntityRepository $er) {
        return $er->createQueryBuilder('u')
            ->orderBy('u.username', 'ASC');
    },
));

如何将query_builder函数移动到外部类并从表单类型中的该类访问查询方法。我的想法是使代码更加模块化,更好,因此FormType不会自己连接到db,而是使用例如Entity的EntityRepository类

想要的代码(摘要):

use Acme\HelloBundle\UserRepository;
// ...
'query_builder' = UserRepository->getSortedList();

1 个答案:

答案 0 :(得分:0)

我假设您在2014年使用过Symfony 2.3,因此您应该使用choices。只需将它们或存储库包含在options数组中,因此表单不会连接到db

  1. 包含选择
  2. 
    
        // in controller
        $object = ...;
        $form = $this->createForm(new SomeObjectType(), $object, array('user_choices' => $userRepository->getSortedList()));
    
        // in SomeOjectType
        $builder->add('users', 'entity', array(
            'class' => 'AcmeHelloBundle:User',
            'choices' => $options['user_choices'],
        ));
        ...
        // in setDefaultOptions method
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                ...
                'user_choices' => array(),
            ));
        }
    
    
    1. 包含存储库
    2. 
      
          // in contoller
          $object = ...;
          $form = $this->createForm(new SomeObjectType(), $object, array('repository' => $userRepository));
      
      
          // in SomeOjectType
          $builder->add('users', 'entity', array(
              'class' => 'AcmeHelloBundle:User',
              'choices' => $options['repository']->getSortedList(),
          ));
          ...
          // in setDefaultOptions method
          public function setDefaultOptions(OptionsResolverInterface $resolver)
          {
              $resolver->setDefaults(array(
                  ...
                  'repository' => null,
              ));
          }
      
      

      我希望这会对有类似问题的人有所帮助