简体   繁体   中英

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 ! 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. 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. 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. 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. Cause it's really different that what was used in 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 :

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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