Symfony2: Edit user without having password

Until I see a more elegant solution, here's what I came up with:

  1. Create a UserEditType form class with all fields but the password field(s)
  2. Assign UserEditType to a validation group other than Default
  3. Configure the password length constraint to the validation group in 2.
  4. Modify the edit and update actions to use UserEditType

And now users can be edited without having the password!

UserEditType:

class UserEditType extends AbstractType {
    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('role', 'choice', array(
                    'choices' => array('ROLE_USER' => 'User', 'ROLE_ADMIN' => 'Admin'),
                    'expanded' => true,
                    'multiple' => false,
                    'label' => 'Group: ',
                ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'Mana\ClientBundle\Entity\User',
            'validation_groups' => array('edit'),
        ));
    }

Password in User entity:

 * @ORM\Column(name="userpass", type="string", length=100, nullable=false)
 * @Assert\NotBlank(message="Password may not be empty")
 * @Assert\Length(
 *      min = "5",
 *      max = "12",
 *      minMessage = "Password must be at least 5 characters long",
 *      maxMessage = "Password cannot be longer than than 12 characters",
 *      groups = {"Default"}
 * )

Update action:

public function updateAction(Request $request, $id) {
    $em = $this->getDoctrine()->getManager();
    $user = $em->getRepository('ManaClientBundle:User')->find($id);

    $form = $this->createForm(new UserEditType(), $user);
    $form->bind($request);
    if ($form->isValid()) {
        $em->persist($user);
        $em->flush();
        return $this->redirect($this->generateUrl('user_main', array()));
    }
    return array(
        'form' => $form->createView(),
        'user' => $user,
        'title' => 'Edit user',
    );
}

I've had the same problem here in my project.

I solved it by removing the password field from the form just for my edit action.

So, in my UserController, I changed the editAction:

//find the line where the form is created
$editForm = $this->createForm(new UserType($this->container), $entity)
        ->remove('password'); //add this to remove the password field