在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 ...
可能有解决方法吗?有什么想法吗?
答案 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);
});
}
}