Symfony2 - 仅在填充其中一个字段时验证一组字段(并更改值)

时间:2014-04-05 14:16:00

标签: forms validation symfony

我正在处理个人资料编辑表单类型。我有问题如何验证字段oldPasswordpassword,只有当其中一个字段被填充时才会有效。首先我设置了required => false,但我无法找到关闭验证的方法,只有在填充了字段oldPassword或重复字段password时才会启用。此外,如果未进行验证,则不会将这些字段的值处理为DB。

在表单类型类中我有:

        ->add('oldPassword', 'password', array('label' => 'Old password', 'required' => false, 'mapped' => false, 'error_bubbling' => true))
        ->add('password', 'repeated', array('type' => 'password', 'required' => false, 'invalid_message' => 'New passwords must equal', 'first_options'  => array('label' => 'New password'), 'second_options' => array('label' => 'Repeat new password'), 'error_bubbling' => true,))

在我的实体中:

/**
 * @ORM\Column(type="string", length=255)    
 * @Assert\Length(
 *      min = "4",
 *      minMessage = "Password must have at least 4 characters"         
 * )       
 */
private $password;

/**
 * @SecurityAssert\UserPassword(
 *     message = "Old password must equal with current"
 * )
 */
protected $oldPassword;

在控制器中没什么特别的:

public function profileAction(Request $request)
{
    if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
        throw new AccessDeniedException();
    }

    $em = $this->getDoctrine()->getManager();
    $user = $this->getUser();

    if(!$user)
    {
        $this->get('session')->getFlashBag()->add(
            'error',
            'User with ID ' . $user->getId() . ' does not exist'
        );
        return $this->redirect($this->generateUrl('admin_dashboard'));
    }

    $form = $this->createForm('user', $user);
    $form->handleRequest($request); 

    if($form->isValid())
    {
        $em->persist($user);

        try {
            $em->flush();
        } catch (\PDOException $e) {
            // sth
        }
        $this->get('session')->getFlashBag()->add(
            'success',
            'Profile was successfuly edited'
        );

        $em->refresh($user);
    }

    return $this->render('AcmeUserBundle:Admin:profile.html.twig', array('form' => $form->createView()));
}

现在我需要这些字段(oldPasswordpassword)在未填充且不会更改当前值时不会被验证,因为还有更多字段,例如{{1 }},usernameemail

这适用于FormType或Controller或两者兼有吗?

0 个答案:

没有答案