gpt4 book ai didi

php - 交响乐 3 : Passing variables into forms

转载 作者:可可西里 更新时间:2023-11-01 00:18:50 25 4
gpt4 key购买 nike

我正在使用 Symfony 3 Forms 构建,并且需要在表单中检索依赖于当前用户的集合以在下拉列表中呈现。

使用 EntityType 我可以检索所有实体的列表,但我希望能够运行自定义查询,该查询仅检索与当前用户对象有关系的实体。

我已阅读有关表单和 EntityType 的文档,其中解释了自定义查询并提到将集合作为参数传递。但我在任何地方都找不到关于如何实现这一点的说明。

理想情况下,我想传入一个我在 Controller 中策划的集合,传入用户对象以在表单内运行查询,或者以其他方式访问表单中的用户 ID 以运行查询.

有没有人找到类似的解决方案?

最佳答案

你应该试试

pass in the User object to run the query inside the Form

  1. options resolver 中定义必需的参数user :

    public function configureOptions(OptionsResolver $resolver)
    {
    // ...
    $resolver->setRequired('user');
    // type validation - User instance or int, you can also pick just one.
    $resolver->setAllowedTypes('user', array(User::class, 'int'));
    }

它会强制您传递 user 选项,这样您就不会忘记它。

  1. 将用户实例或用户 ID 作为选项传递到表单中。

在 Controller 中它可能看起来像这样:

$this->createForm(SomeFormType::class, $underlyingObjectOrNull, array(
'user' => $this->getUser(),
));
  1. 构建一个 custom query for EntityType领域:

    $user = $options['user'];
    $builder->add('someField', EntityType::class, array(
    'class' => 'AppBundle:SomeEntity',
    'query_builder' => function (EntityRepository $er) use($user) {
    return $er->createQueryBuilder('u')
    //.. -> some method building the query builder
    },
    ));

请注意 use($user) 部分,它使您可以在匿名函数中访问此变量。

关于php - 交响乐 3 : Passing variables into forms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43092246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com