首页 文章

Symfony2验证不适用于重复字段(密码确认)

提问于
浏览
0

我是Symfony2的初学者 . 我阅读了食谱,并在互联网上搜索,但我找不到我的问题的答案 .

这是我的表格类型:

/**
 * Builds a form with given fields.
 *
 * @param object  $builder A Formbuilder interface object
 * @param array   $options An array of options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('password', 'repeated', array(
        'first_name' => 'password',
        'second_name' => 'confirm',
        'type' => 'password',
        'invalid_message' => 'Passwords do not match'
    ));
}
/**
 * Sets the default form options
 *
 * @param object $resolver An OptionsResolver interface object
 */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Opit\Notes\UserBundle\Entity\User',
    ));
}
/**
 * Get the name
 *
 * @return string name
 */
public function getName()
{
    return 'user';
}

用户是一个实体

这是树枝:

<form name="changePassword_frm" id="changePassword_frm" method="post">
<div class="modalwindow width-98 default-border height-auto overflow-hidden">
        {{ form_widget(form) }}
</div>

和我的用户控制器中的功能(由ajax请求调用)

public function updatePasswordAction()
{
    $result = array('response' => 'error');
    $request = $this->getRequest();        
    $em = $this->getDoctrine()->getManager();

    $user = $this->getUserObject($request->attributes->get('id'));

    $form = $this->createForm(new ChangePasswordType(), $user);

    if ($request->isMethod("POST")) {
        $form->handleRequest($request);        

        if ($form->isValid()) {
            $encoder = $this->container->get('security.encoder_factory')->getEncoder($user);
            $newPassword = $encoder->encodePassword($user->getPassword(), $user->getSalt());
            $user->setPassword($newPassword);

            // Save the user.
            $em->persist($user);
            $em->flush();
            $result['response'] = 'success';
        }
    }
    return new JsonResponse(array($result)); 
}

验证不起作用,例如,如果我只填写第一个字段(确认 - 第二个字段没有) . 这是有效的!...所以valid()方法不检查两个字段的值是否相等......

但是,如果我只填写'password'字段而'fill'字段不是......那么数据库中的密码将是哈希空字符串 . 如果我填写两者,它们是相同的 . 它将是数据库中的给定密码 . (它有效,因为我可以登录到我的页面) .

但我不知道,为什么验证不起作用?为什么我没有收到任何错误消息?我检查过,总是进入isValid()方法...总是 .

1 回答

  • 0

    您需要使用first_options和second_options作为参数 . 看起来你正在使用first_name和second_name . 尝试更改您的FormType:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('password', 'repeated', array(
            'type' => 'password',
            'first_options' => array('label' => 'Password'),
            'second_options' => array('label' => 'Confirm'),
            'invalid_message' => 'Passwords do not match'
        ));
    }
    

    这将通过实际字段为您提供字段的名称,而不是JUST字段的名称 . 默认情况下,此方法包含验证 .

相关问题