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

EntityType inside CollectionType: Get current object inside query_builder

CollectionType 中使用 EntityType 时,是否可以在 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说不可能:

When using a callable, you will be passed the EntityRepository of the entity as the only argument...

是否有解决方法?有什么想法吗?

您可以使用 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);
        });

    }
}