In my application, only the admin user can create and, theoretically, edit users. Until now, using only the Symfony security system (without FOSUserBundle management - its complexity is not required), creating users with different roles is normal. The problem that completely eludes me is how to edit the user without knowing the user password. I continue to work with the expected validation error
Password cannot be empty
. How can I edit? Of course, I missed something very important here.
Change action:
public function editAction($id) { $em = $this->getDoctrine()->getManager(); $user = $em->getRepository('ManaClientBundle:User')->find($id); $form = $this->createForm(new UserType(), $user); return array( 'form' => $form->createView(), 'user' => $user, 'title' => 'Edit user', ); }
Update action:
public function updateAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $user = $em->getRepository('ManaClientBundle:User')->find($id); $originalPassword = $user->getPassword(); $form = $this->createForm(new UserType(), $user); $form->bind($request); if ($form->isValid()) { $plainPassword = $form->get('password')->getData(); if (!empty($plainPassword)) { //encode the password $encoder = $this->container->get('security.encoder_factory')->getEncoder($entity); //get encoder for hashing pwd later $tempPassword = $encoder->encodePassword($entity->getPassword(), $entity->getSalt()); $user->setPassword($tempPassword); } else { $user->setPassword($originalPassword); } $em->persist($user); $em->flush(); return $this->redirect($this->generateUrl('user_main', array())); }
User Form:
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('enabled', 'choice', array( 'choices' => array('Yes' => 'Yes', 'No' => 'No'), 'expanded' => true, 'multiple' => false, 'label' => 'Enabled: ', )) ->add('fname') ->add('sname') ->add('email') ->add('username') ->add('password', 'repeated', array( 'type' => 'password', 'invalid_message' => 'Password fields do not match', 'first_options' => array('label' => 'Password'), 'second_options' => array('label' => 'Repeat Password'), )) ->add('role', 'choice', array( 'choices' => array('ROLE_USER' => 'User', 'ROLE_ADMIN' => 'Admin'), 'expanded' => true, 'multiple' => false, 'label' => 'Group: ', )) ; }