如何将完整的安全角色列表/层次结构传递给 Symfony2 中的 FormType 类? [英] How can I pass a full security roles list/hierarchy to a FormType class in Symfony2?

查看:30
本文介绍了如何将完整的安全角色列表/层次结构传递给 Symfony2 中的 FormType 类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户编辑表单,我想在其中管理分配给用户的角色.

I have a user edit form where I would like to administer the roles assigned to a user.

目前我有一个多选列表,但我无法使用 security.yml 中定义的角色层次结构填充它.

Currently I have a multi-select list, but I have no way of populating it with the role hierarchy defined in security.yml.

是否可以通过某种方式将这些信息传递给 FormType 类中的表单构建器?

Is there some way that I get this information to the form builder in the FormType class?

$builder->add('roles', 'choice', array(
                'required' => true,
                'multiple' => true,
                'choices' => array(),
            ));

环顾四周我发现我可以从控制器中的容器中获取角色:

Looking around I found that I can get the roles from the container in a controller with:

$roles = $this->container->getParameter('security.role_hierarchy.roles');

我还发现我可以将其设置为要注入到 services.xml 中的 FormType 类的依赖项:

I have also discovered that I could potentially set this as a dependency to be injected on the FormType class in services.xml:

<parameters>
    <parameter key="security.role_heirarchy.roles">ROLE_GUEST</parameter>
</parameters>
<services>
    <service id="base.user.form.type.user_form" class="Base\UserBundle\Form\UserType" public="false">
        <tag name="form.type" />
        <call method="setRoles">
            <argument>%security.role_heirarchy.roles%</argument>
        </call>
    </service>
</services>

然而这不起作用,而且似乎从未调用过 setRoles 方法.

This however does not work and does not seem to ever call the setRoles method.

那么我怎样才能让它发挥作用?

So how can I get this to work?

推荐答案

在你的控制器中

$editForm = $this->createForm(new UserType(), $entity, array('roles' => $this->container->getParameter('security.role_hierarchy.roles')));

在用户类型中:

$builder->add('roles', 'choice', array(
    'required' => true,
    'multiple' => true,
    'choices' => $this->refactorRoles($options['roles'])
))

[...]

public function getDefaultOptions()
{
    return array(
        'roles' => null
    );
}

private function refactorRoles($originRoles)
{
    $roles = array();
    $rolesAdded = array();

    // Add herited roles
    foreach ($originRoles as $roleParent => $rolesHerit) {
        $tmpRoles = array_values($rolesHerit);
        $rolesAdded = array_merge($rolesAdded, $tmpRoles);
        $roles[$roleParent] = array_combine($tmpRoles, $tmpRoles);
    }
    // Add missing superparent roles
    $rolesParent = array_keys($originRoles);
    foreach ($rolesParent as $roleParent) {
        if (!in_array($roleParent, $rolesAdded)) {
            $roles['-----'][$roleParent] = $roleParent;
        }
    }

    return $roles;
}

这篇关于如何将完整的安全角色列表/层次结构传递给 Symfony2 中的 FormType 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆