CollectionType内部的EntityType:在query_builder中获取当前对象

时间:2019-03-25 13:53:01

标签: php symfony symfony-forms

EntityType内使用CollectionType时,是否可以在EntityType的query_builder函数内访问当前集合对象?

主要形式:

class UsersType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('users', CollectionType::class, array('entry_type' => UserType::class));
    }
}

子表单:

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('mainPost', EntityType::class, array(
                'class' => Post::class,
                'query_builder' => function (PostRepository $postRepository) {
                    return $postRepository->findPostsOfUser(); // <= Here I'd like to pass the *current* user to the repository
                },
            ))
        ;
    }
}

原因:我不想看到每个用户的所有帖子,而只希望看到该用户的帖子。

EntityType's docs说不可能:

  

使用可调用对象时,您将作为 only 参数传递给实体的EntityRepository ...

可能有解决方法吗?有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用FormEvents来解决。在PRE_SET_DATA事件中,将设置单个用户实体的数据。您可以这样覆盖它:

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('mainPost', EntityType::class, array(
                'class' => Post::class,
            ))
        ;

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
            $user = $event->getData();
            $form = $event->getForm();

            $field = $form->get('mainPost');
            $options = $field->getConfig()->getOptions();
            $options['query_builder'] = function (PostRepository $postRepository) use ($user) {
                return $postRepository->findPostsOfUser($user);
            };

            $form->add($field->getName(), EntityType::class, $options);
        });

    }
}