Symfony sfForm密码(必填和比较)

时间:2012-01-11 18:39:46

标签: php symfony1

在symfony中。 。 。我的表格看起来像这样

<?php

class ChangeMyPasswordForm extends sfForm {

    const PASSWORD_REQUIRED_MSG = "We could not update your password. Your password can not be blank. Please enter at least one character for a password.";

    protected static $labels = array(
            'password' => 'Your Password',
        'confirm'  => 'Re-enter Password',
    );

    public function configure()
    {   
        $this->setWidgets(array(
           'password'  => new sfWidgetFormInputPassword(array()),
             'confirm' => new sfWidgetFormInputPassword(array()),
        ));

        $this->setValidators(array(
            'password' => new sfValidatorPass(),
             'confirm' => new sfValidatorPass(),
        ));

        $this->validatorSchema->setOption('allow_extra_fields', true); 

        $this->mergePostValidator(
            new sfValidatorSchemaCompare('password', sfValidatorSchemaCompare::IDENTICAL, 
                'confirm', array(), array(
                    'invalid'=>'Passwords do not match. Please try again.'
                )
            )
        );

        $this->mergePostValidator(new sfValidatorString());
        $this->widgetSchema->setLabels(self::$labels);
    }
}

在我的控制器中

public function executeMyAccountPassword(sfRequest $request) {
      $this->form = new ChangeMyPasswordForm();
      $this->validated=$request->getParameter('validated');

      $this->form->bind(array(
              'password' => $request->getParameter('password'),
              'confirm'  => $request->getParameter('confirm'),
      ));

      if ($request->isMethod('post')) {

          if ($this->form->isValid()) {
              $this->validated = true;

              // get player object
              $player = $this->getUser()->getProfile();
              $player->setPassword($request->getParameter('password'));
          }
      }

我正在尝试添加验证程序,因此密码字段不能为空。我尝试修改

$this->setValidators(array('password'=>new sfValidatorString('required'=>'Please enter a password')));

但即使没有发布数据,表单也会出现错误。任何人都可以告诉我一个如何验证两个匹配的密码字段的正确示例,并确保字段不留空(在表单提交后)。谢谢!!

2 个答案:

答案 0 :(得分:2)

你有第二个错误。在if下面将绑定向下移动几行。这意味着您应该使用发布的

进行绑定
if ($request->isMethod('post')) 
{
  $this->form->bind(array(
    'password' => $request->getParameter('password'),
    'confirm'  => $request->getParameter('confirm'),
  ));

  ... etc...
}

答案 1 :(得分:1)

$ this-setValidators上有语法错误。你遗漏了几个括号:

$this->setValidators(array('password'=>new sfValidatorString('required'=>'Please enter a password')));