【问题标题】:Symfony Form Type - add optionsSymfony 表单类型 - 添加选项
【发布时间】:2020-03-05 15:41:26
【问题描述】:

在我的项目中,我有 3 个实体;用户、模块和用户模块。

User 具有 id、username、email 等属性以及作为 UserModules 集合的 UserModules 属性。

模块具有属性 id、name 和 description。

每个 UserModule 对象都有属性 User(引用对应的 User)、Module(引用对应的模块)和 Access(是否允许访问的布尔值)

我的问题是我不知道如何在创建用户时使用 Symfony 的表单类型来显示所有模块。 我已经制作了许多模块(即“admin”、“ticket”、“help”)。在我的 UserType 类中,我的 buildForm 方法如下所示:

    {
        $builder
            ->add('username')
            ->add('email')
            ->add('modules', CollectionType::class, [
                'entry_type' => UserModuleType::class,
                'entry_options' => [
                    'label' => false
                ],
            ]);
    } 

我的 UserModuleType 类是

    {
        $builder
            ->add('access', ChoiceType::class, [
                'choices' => [
                    'No Access' => false,
                    'Full Access' => true,
                ]
            ]);
    }

这显示了分配给用户的 UserModules,但是在创建用户时,我希望它已经为每个模块添加了 UserModules。

我该如何设置,以便表单使用所有可能的模块来创建默认的 UserModules?

【问题讨论】:

  • 再想一想,也许我应该在创建新用户之后、在我的 UserController 的新操作中以及在使用它创建表单之前将 UserModules 添加到我的 User 类中 ' $user = new User() / /code 创建和添加用户模块 $form -> $this->createForm(UserType::class, $user)'

标签: forms symfony formbuilder symfony5


【解决方案1】:

我希望你能在这里找到一些帮助: https://symfony.com/doc/current/form/form_collections.html

在示例中:使用标签作为您的模块

【讨论】:

    【解决方案2】:

    在这种情况下,由于您仅使用 true 和 false 来定义用户是否有权访问模块,因此我将使用带有 multiple 属性的 EntityType 而不是 CollectionType。

    这样你只设置哪些模块可以访问。

    Link to documentation

    【讨论】:

      猜你喜欢
      • 2013-11-23
      • 1970-01-01
      • 2020-10-28
      • 2023-03-16
      • 2019-10-02
      • 2022-06-10
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多