symfonyfosuserbundle

How to create a form to edit user roles with FriendsOfSymfony UserBundle


I'm trying to create a controller where I can edit the roles of a user (just that, nothing else) and I'm king of stuck.

I've created a form type:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add(
            'roles', 'choice', [
                'choices' => ['ROLE_ADMIN', 'ROLE_USER', 'ROLE_CUSTOMER'],
                'expanded' => true,
                'multiple' => true,
            ]
        )
        ->add('send', 'submit');
}

First, what would be the best way to retrieve the roles? Is there any way to associate a label to them?

In the controller I have this:

/**
     * User role edition
     *
     * @Route(
     *      path="/edit-roles",
     *      name = "backoffice_user_edit_roles",
     *      requirements = {
     *          "id_user" = "\d*",
     *      },
     *      methods = {"GET"}
     * )
     *
     * @Security("has_role('ROLE_ADMIN')")
     *
     * @Template
     */
    public function editRolesAction($id_user)
    {
        $user = $this->user_repository->findOneById($id_user);
        $form = $this->form_factory->create('dirital_user_roles_form_type', $user);
        return [
            'form' => $form->createView(),
            'user' => $user
        ];
    }

Problems that I have:

Thanks a lot


Solution

  • Actually it was easier than I thought – this is the form:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add(
                'roles', 'choice', [
                    'choices' => ['ROLE_ADMIN' => 'ROLE_ADMIN', 'ROLE_USER' => 'ROLE_USER', 'ROLE_CUSTOMER' => 'ROLE_CUSTOMER'],
                    'expanded' => true,
                    'multiple' => true,
                ]
            )
            ->add('save', 'submit', ['label' => 'ui.button.save']);
    }
    

    And the controller:

    public function editRolesAction(Request $request, $id_user)
    {
        $user = $this->user_repository->findOneById($id_user);
        $form = $this->form_factory->create('dirital_user_roles_form_type', $user);
        $form->handleRequest($request);
        if($form->isValid())
        {
            $this->addFlash('success', 'section.backoffice.users.edit_roles.confirmation');
            $this->em->persist($user);
            $this->em->flush();
            $this->redirectToRoute('backoffice_user_edit_roles', ['id_user' => $user->getId()]);
        }
        return [
            'form' => $form->createView(),
            'user' => $user
        ];
    }
    

    The only part that remains to do is grabbing the form choices from the config instead of hardcoding them.