2012-01-11 57 views
0

在symfony中。 。 。我的形式看起来像这样Symfony sfForm密码(必需和比较)

<?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'))); 

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

+0

的结合? 1.4? – MrGlass 2012-01-11 18:45:24

+0

另外,你得到了什么错误? – MrGlass 2012-01-11 18:45:49

+0

Yessir。 。 。 1.4没有收到错误。它会呈现错误消息“密码不匹配”的表单。请再试一次。'这是正确的信息,我只需要它在表单发布后运行验证器。 – TuK 2012-01-11 18:48:23

回答

2

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

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

    ... etc... 
} 
您正在使用什么版本的symfony
1

您在$ this-setValidators中有语法错误。你失踪了几个括号:

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

+0

对不起回合 - 当我编写后,一定是一种类型 - 现在编辑它。当我添加此行时,表单会在渲染后立即吐出错误消息。 - 当然,这个字段是空白的,表单刚刚呈现,用户还没有输入任何内容。 – TuK 2012-01-11 18:55:06