setValidator() in action class


setValidator() in action class

我有一个问题,当我试图使用setValidator()(不是setValidators)在行动类文件。

这是我的基本形式类代码。

public function setup()
  {
    $this->setWidgets(array(
      'id'         => new sfWidgetFormInputHidden(),
      'name'       => new sfWidgetFormInputText(),
      'age'        => new sfWidgetFormChoice(array('choices' => array('21' => '21', '22' => '22', '23' => '23', '24' => '24', '25' => '25', '26' => '26', '27' => '27', '28' => '28', '29' => '29', '30' => '30'))),
      'gender'     => new sfWidgetFormChoice(array('choices' => array('Male' => 'Male', 'Female' => 'Female'))),
      'email'      => new sfWidgetFormInputText(),
      'salt'       => new sfWidgetFormInputText(),
      'password'   => new sfWidgetFormInputPassword(array('type' => 'password')),
      'created_at' => new sfWidgetFormDateTime(),
      'updated_at' => new sfWidgetFormDateTime(),
    ));
    $this->setValidators(array(      
      'id'         => new sfValidatorPass(),    
      'name'       => new sfValidatorString(array('required' => true)),
      'age'        => new sfValidatorPass(),      
      'gender'     => new sfValidatorChoice(array('choices' => array('Male','Female'))),
      'email'      => new sfValidatorEmail(array('required' => true)),
      'password'   => new sfValidatorString(array('required' => true)),
      'created_at' => new sfValidatorDateTime(),
      'updated_at' => new sfValidatorDateTime(),
    ));
    $this->widgetSchema->setNameFormat('signin[%s]');
    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    //$this->validatorSchema->setPostValidator(new sfUserValidate());
    $this->setupInheritance();
    parent::setup();
  }

这是我的动作类代码…

public function executeNewuser($request)
  {
      $this->form = new UsersForm();
      $this->form->getWidgetSchema()->setNameFormat('users[%s]');
      //$this->form->setValidators(array('name' => new sfValidatorDoctrineUnique(array('model'  => 'Users','column' => 'name'))));
      $this->form->setValidator(array('name' => new sfValidatorDoctrineUnique(array('model'  => 'Users','column' => 'name'))));

      if($request->isMethod('post'))
      {
        $this->form->bind($request->getParameter('users'));
        if($this->form->isValid())
        {      
            echo "Hello";exit;
        }  
      }
  }

我得到以下错误

可捕获的致命错误:参数2传递给sfForm::setValidator()必须是sfValidatorBase的一个实例,没有给出,在/home/hardik/web/demo/apps/frontend/modules/user/actions/actions.class.php第77行

我只需要在action类中重写name字段的验证器。

你的语法错误。看setValidator的签名。你应该这样做:

$this->form->setValidator(
  'name', 
  new sfValidatorDoctrineUnique(array('model'  => 'Users','column' => 'name')));