简体   繁体   中英

Symfony Fos User Bundle : Link fos_user_group and roles

I configured a Users management thanks to Sonata User Bundle and FOS User Bundle. I made some groups with permissions, and I put users in it. But when I log in these users profiles, I don't have the roles that I affected to groups.

Does someone have an explanation to that?

FOS uses two functions for the roles that utilize the serialization and unserialization array in addRole and setRoles. You can do it by using the user manager api or the doctrine entity manager, and that is by creating your action in the controller as follows:

public function registerUserAction(Request $request)
{
     $task = new User();


    $form = $this->createFormBuilder($task)
        ->add('username', 'text')
        ->add('email', 'email')
        ->add('enabled', 'choice', array(
              'choices'   => array('Enable' => 1, 'Disable' => 0),
              'required'  => true,

          ))   
        ->add('password', 'password')
        ->add('roles')     
        ->add('save', 'submit')
        ->getForm();
    $form->handleRequest($request);

    if($form->isValid()){
   $username = $form->get('username')->getData();
   $email = $form->get('email')->getData();
   $pass = $form->get('password')->getData();
   $enabled = $form->get('enabled')->getData();
   $roles = $form->get('roles')->getData();



   $task->setUsername($username);
   $task->setEmail($email);
   $task->setPlainPassword($pass);

   $task->setRoles($roles);
   $task->setEnabled($enabled);

   $em = $this->getDoctrine()->getManager();
   $em->persist($user);
   $em->flush();

    }
    return $this->render('SafUserBundle:ManageUser:registerUser.html.twig', array(
        'form' => $form->createView(),
    ));


}

Make sure enabling the library for http requests at the top of the controller as follows:

use Symfony\\Component\\HttpFoundation\\Request;

The above will glue the template and the controller in using the form.

in the twig you can output the form all at once {{ form(form) }} or you can write it field by field if you want full control over the render.

The roles property in the User class is an array therefore type conversion is used in addRole

alternatively you can use the user manager provided by the fosuserbundle

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