How to create a form for editing a user role using FriendsOfSymfony UserBundle

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

I 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 off, what's the best way to get roles? Is there a way to associate a label with them?

In the controller, I have the following:

/**
     * 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
        ];
    }

The problems that I have are:

  • The form is not populated with the current user roles, how can I do this?
  • When I receive the form, how can I update the user?

thanks a lot

+4
source share
1 answer

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

, , - .

+6

Source: https://habr.com/ru/post/1614466/


All Articles