sfFormの複数項目バリデータ

  • sfFormのバリデータ指定はフィールド単体に対するものが基本となっています。
  • では、“検索条件等のフォームでは年齢の範囲指定をしたい”のように、FROM・TOと2つの項目を合わせてチェックしたい場合、どのように指定するのでしょうか。
  • setPostValidatorを使用して、下記のように記述することで実現できます。
class hogeForm extends BaseForm
{
    public function configure()
    {
        $this->setWidgets(array(
            'age_from'              => new sfWidgetFormInputText(),
            'age_to'                => new sfWidgetFormInputText(),
        ));

        $this->getValidatorSchema()->setPostValidator(
           // '<='等の比較演算子文字列は、sfValidatorSchemaCompareクラス内に定数宣言もありますが、このほうが分かりやすいように思います。
           new sfValidatorSchemaCompare('age_from', '<=', 'age_to')
        );

        $this->getWidgetSchema()->setNameFormat('hogeinput[%s]');
        $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);
    }
}

postValidator内に複数のバリデータを設定するには

  • 上記で複数項目のチェックはできました。では、上記に加えて、勤続年数範囲条件も追加する場合。
  • 下記のように sfValidatorAnd を使用して実現できます。
class hogeForm extends BaseForm
{
    public function configure()
    {
        $this->setWidgets(array(
            'age_from'              => new sfWidgetFormInputText(),
            'age_to'                => new sfWidgetFormInputText(),
            'work_length_from'      => new sfWidgetFormInputText(),
            'work_length_to'        => new sfWidgetFormInputText(),
        ));

        $this->setValidators(array(
            'age_from'              => new sfValidatorInteger(),
            'age_to'                => new sfValidatorInteger(),
            'work_length_from'      => new sfValidatorInteger(),
            'work_length_to'        => new sfValidatorInteger(),
        ));

        $this->getValidatorSchema()->setPostValidator(new sfValidatorAnd(array(
            new sfValidatorSchemaCompare('age_from', '<=', 'age_to'),
            new sfValidatorSchemaCompare('work_length_from', '<=', 'work_length_to'),
        )));

        $this->getWidgetSchema()->setNameFormat('hogeinput[%s]');
        $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);
    }
}

先行するチェックがエラーの場合、バリデートをそこでやめる

  • チェック項目が2つあり、1つ目がエラーなら、2つ目はチェックしないほうが良い場合。
$this->getValidatorSchema()->setPostValidator(new sfValidatorAnd(array(
    new sfValidatorSchemaCompare('age_from', '<=', 'age_to'),
    new sfValidatorSchemaCompare('work_length_from', '<=', 'work_length_to'),
    ), array('halt_on_error' => true)
));

facebook slideshare rubygems github qiita