Search code examples
symfonyeditfosuserbundlerole

FOSUserBundle show group roles in edit view


I'm trying by overriding the controller and the formtype, to show the roles from the selected group in my view, but I don't find the right way. I've followed the steps to override everything, that works, but problem comes when I try to say to the service that I'm passing to the constructor an entity object.

As the formtype has to be overridden, how to pass through the service that you need to implement, my Group entity?

Does anyone have an idea of how to achieve that?

Here's what I've done:

  1. Override the controller, and when creating the Form, pass the $group entity

    $formFactory = $this->container->get('fos_user.group.form.factory');
    $form = $formFactory->createForm($group);  //Here
    
  2. Override the form, and use a custom __construct method where I can pass my entity (maybe here is my error and that should be done in a better or other way)

    public function __construct(Container $container, Groups $group)
    {
        $this->container = $container;
        $this->roles = array_keys($this->container->getParameter('security.role_hierarchy.roles'));
    
        $this->group = $group; #How? 
    }
    

The container to get the keys for the roles is passed without errors, that works.

  1. Create the service as the documentation says (here comes the real problem and the exceptions)

     x_s_cosmos.group.form.type:
        class: X\S\CosmosBundle\Form\Type\GroupFormType
        arguments: [@service_container, here_should_be_my_entity?]
        tags:
            - { name: form.type, alias: kosmos_group_form }
    

I'm really stacked with that and don't have any idea of how to go on.


Solution

  • Finally, after overriding the GroupController.php and adding a choice field type to my form, I could achieve my goal.

        $form->add('roles', 'choice', array(
                    'choices' => $this->getExistingRoles(),
                    'data' => $group->getRoles(),
                    'label' => 'Roles',
                    'expanded' => true,
                    'multiple' => true,
                    'mapped' => true,
                ));
    

    Where getExistingRoles() is:

        $roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
        $roles = array_keys($roleHierarchy); 
    
        foreach ($roles as $role) {
            $theRoles[$role] = $role;
        }
        return $theRoles;
    

    I was just going in the wrong way, it was not so difficult to get the roles of a group and show them in an admin interface so that you can choose one of your system roles and give it to the group. No need to override the FormType, just the controller to add your own fields to the form.

    Hope it helps, as it has given lot of headache to me.