简体   繁体   English

Symfony3-FOSUserBundle-角色归属

[英]Symfony3 - FOSUserBundle - Roles attribution

First of all, i'm french so i beg your pardon for my poor english. 首先,我是法国人,所以请原谅我可怜的英语。

I come to you cause here i am, i'm starting my first Symfony3 project ! 我来找你,因为我在这里,我正在开始我的第一个Symfony3项目! And i got my first problem: I want to use FOSUserBundle to manage my users, but i dont want any visitor to be able to register. 我遇到了第一个问题:我想使用FOSUserBundle来管理我的用户,但是我不希望任何访问者都能注册。 I want the administrator to create the users (i think i can do it), but i need that in the user creation form, the administrator can assign a role to the user. 我希望管理员创建用户(我想我可以做到),但是我需要在用户创建表单中,管理员可以为用户分配角色。 (Just one role) (仅一个角色)

Here's my problem: Symfony3 changed a lot in this point, and the solutions I found dont match anymore. 这是我的问题:Symfony3在这一点上发生了很大变化,而我发现的解决方案不再匹配。 Infact, I would like to add a field CollectionType in the /registration of FOSUserBundle and put this registration page under /admin/registration for making the administrators able to create new users. 实际上,我想在FOSUserBundle的/ registration中添加一个字段CollectionType并将此注册页面放在/ admin / registration下,以使管理员能够创建新用户。 I will change the registration redirection to make the website dont think that the administrator is a visitor using the form. 我将更改注册重定向,以使网站不认为管理员是使用表单的访客。 Is that a good idea? 这是一个好主意吗? Well, I need someone to simply give me the code of the "->add('role')" .. please :D. 好吧,我需要有人简单地给我“-> add('role')”的代码..请:D。 Cause it's really different that what was used in Symfony2. 因为与Symfony2中使用的完全不同。

So, what i want is something like: 所以,我想要的是这样的:

    // \FOS\UserBundle\Form\Type\RegistrationFormType.php


$builder ->add('roles', CollectionType::class, array(
                'entry_type' => TextType::class,
                'entry_options' => array(
                    '/* CHOICES */' => array(
                        /*List of Roles from security.yml*/
                    )
                )
            );

Thanks everyone ! 感谢大家 !

You have to use choices form type 您必须使用选择表单类型

An example to get the roles in Symfony : 在Symfony中获得角色的示例:

In you controller 在您的控制器中

// ... your function
$user = new User();
$roles = $this->container->getParameter('security.role_hierarchy.roles');
$myForm = $this->createForm(new UserType($roles), $user);

$builder->add('roles', 'choice', array(
        'choices' => $this->flattenArray($this->roles),
));

// ... your code

// transform symfony roles into one dimensional array.
public function array_flatten($array)
{
    if (!is_array($array)) {
        return FALSE;
    }
    $result = array();
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $result = array_merge($result, array_flatten($value));
        } else {
            $result[$key] = $value;
        }
    }
    return $result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM