在自身内部编辑自定义 SF3 类型

Edit custom SF3 type inside itself

我扩展了 ChoiceType 以创建一个 RolesType,其目标是提供多个可选择的应用程序自定义角色列表。

由于我的角色在 config.yml 中定义,我 不希望 为每个 RolesType 用法传递它,例如:

$builder
->add('authorizedRoles', RolesType::class, [
                'label' => static::ROOT_TRANSLATION_PATH . ".roles.label",
                'multiple'  => true,
                'expanded'  => false,
                'roles_list' => $roles,
                'attr' => [
                    'helper' => static::ROOT_TRANSLATION_PATH . ".roles.helper",
                ]
            ])

相反,我尝试通过在 RoleType 构造函数中注入角色列表来初始化此选择列表:

    public function __construct(array $rolesData) {
        $this->rolesData = $rolesData;

        foreach($this->rolesData as $roleId => $roleData) {
            $this->rolesList[$roleData['label']] = $roleData['key'];
        }
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->setAttribute('multiple', true);
        $builder->setAttribute('expanded', false);
        $builder->setAttribute('choices', $this->rolesList);

        $options['multiple'] = true;
        $options['expanded'] = false;
        $options['choices'] = $this->rolesList;

//        'multiple'  => true,
//        'expanded'  => false,
//        'choices'   => $this->rolesList,
    }

    public function getParent()
    {
        return ChoiceType::class;
    }

你可以看到我失败的尝试按照表格行事。因为我一直想要我的角色,而且我总是想要多个和扩展的选项具有相同的值,所以在这里做(恕我直言)要好得多。

到目前为止,属性和选项引导失败。 如何在构建器中(或其他地方的表单类型)进行设置?

您提出的想法已被弃用,并在 Symfony 3 中删除。

您可以添加一个新选项并从 Controller 传递角色数组。这就是您在 RoleType class.

中添加选项的方式
public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefined(array('roles_list'));
        $resolver->setAllowedTypes('roles_list', 'array');
    }

你说:

options leads failed

如果这不起作用,请提供错误消息。

您可以将 configureOptions 中的选项设置为默认值,而不是 buildForm

尝试用这个代替 buildForm,但保留你的构造函数:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(   
        'multiple' => true,
        'expanded' => false,
        'choices' => $this->rolesList,
    ));
}

记得使用适当的标签将自定义表单类型注册为服务。

可能是这样的:

services:
    app.form.type.roles:
        class: AppBundle\Form\Type\RolesType
        arguments:
            - '%rolesList%'
        tags:
            - { name: form.type }

实际上Symfony's Doc

中有一个类似的例子