0

Would like to know how can achieve the creation of a new user but specifying his role. At the moment, when i created a new user the program automatically associated with ROLE_ADMIN role.

Any information/code/example is very welcome.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Gabriel Muñumel
  • 1,876
  • 6
  • 34
  • 57
  • Are you sure that **ROLE_ADMIN** is the default role? That seems strange to me. How are you creating the user? – Alessandro Desantis May 28 '12 at 09:00
  • I supposed ROLE_ADMIN is the default role, not sure about it. What i usually do to create a new user is going into `/register` and fill the form. Then, check the authentication on symfony debug panel and it shows the ROLE_ADMIN role assigned. – Gabriel Muñumel May 28 '12 at 18:23

3 Answers3

6

Ok. I solved my problem. Basically i follow this guide, and changed some aspects.

  1. On my model, i added the field for roles: protected $roles = array();
  2. Changed my Form/Type/RegistrationFormType.php and put the following control:

Code:

$user = new UserAdmin();
    $builder->add('roles', 'collection', array(
        'type'   => 'choice',
        'options'  => array(
            'choices'  => array(
                'nashville' => 'Nashville',
                'paris'     => 'Paris',
                'berlin'    => 'Berlin',
                'london'    => 'London',
            ),
        ),
));

Now when i opened my register view it shows a dropdownlist. In this case the options are: Nashville, Paris, Berlin, London.

StefanNch
  • 2,569
  • 24
  • 31
Gabriel Muñumel
  • 1,876
  • 6
  • 34
  • 57
4

This is the code I used:

    $admin = new User() ;
    $admin->setEmail("adminl@gmail.com") ;
    $admin->setUsername("mitke") ;
    $admin->setPlainPassword("123123123") ;
    $admin->setEnabled(true) ;
    $admin->setSuperAdmin(true) ;

    $user1 = new User() ;
    $user1->setEmail("user1@gmail.com") ;
    $user1->setUsername("user1") ;
    $user1->setPlainPassword("123123123") ;
    $user1->setEnabled(true) ;
    $user1->setRoles( array(User::ROLE_DEFAULT) ) ;

Maybe it can help you, it works for me.

Question: Does all users you create using /register has admin role? Maybe FOS decides that first registered user will be admin by default.

Zeljko
  • 5,048
  • 5
  • 36
  • 46
  • I thought it was in that way. But yesterday i tried running the whole register after cleaning my database/cache and the user created was with ROLE_USER role. I will try with your code tonight. Thanks a lot. – Gabriel Muñumel May 30 '12 at 13:25
1

A solution of James Morris could be helpful: http://blog.jmoz.co.uk/symfony2-fosuserbundle-roles

More discuss see: Symfony2 FOSUserBundle Role entities

Community
  • 1
  • 1
Sifeng
  • 713
  • 9
  • 23