在操作Symfony中抛出新的sfValidatorError

时间:2012-01-07 15:49:01

标签: php symfony1 symfony-1.4

我用Doctrine生成的只是动作:

protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $test = $form->save();

      $this->redirect('test/show?id='.$test->getId());
    }
  }

是否可以添加 sfValidatorError ? 例如:

    protected function processForm(sfWebRequest $request, sfForm $form)
      {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));

if(strtotime('now') % 2){
               throw new sfValidatorError('aaa', 'bbb', array();
            } 

        if ($form->isValid())
        {
          $test = $form->save();

          $this->redirect('test/show?id='.$test->getId());
        }
      }

这当然不起作用,因为sfValidatorError必须扩展sfValidatorBase。可以在Symfony 1.4中做到这一点吗?

1 个答案:

答案 0 :(得分:1)

我猜你只想添加新的验证器,而不是抛出sfValidatorError(特别是sfValidatorError必须引用sfValidator抛出它)

遗憾的是,我没有环境来测试这些代码片段,但它们会为您提供一般概念。

首先:创建验证器类

class timestampIsNotEvenValidator extends sfValidatorBase {
    protected function doClean($value) {
        if(strtotime('now') % 2){
           throw new sfValidatorError($this, 'timestamp is not even');
        }
        return $value; //this return is critical!
    }
}

然后:将验证器添加到表单中(但最好在表单配置方法中执行):

protected function processForm(sfWebRequest $request, sfForm $form)
{
    $form->mergePostValidator(new timestampIsNotEvenValidator());
    $form->bind(...);

    if ($form->isValid()) { //false if timestampIsNotEventValidator throwed sfValidatorError
    }

然后,您可以通过调用

在模板中呈现全局错误(由post validator抛出)
//indexSuccess.php
$form->renderGlobalErrors();

或者如果你想将错误绑定到表单的特定字段(即如果表单中有“字段”类型,并且您希望全局验证程序抛出的错误显示为“字段”错误,而不是全局错误,则可以改变你的验证器:

//i dont know if following solution is the best one there is, but it works
class timestampIsNotEvenValidator extends sfValidatorBase {
    protected function doClean($value) {
        if(strtotime('now') % 2){
           throw new sfValidatorErrorSchema($this, array(
               'field' => new sfValidatorError($this, 'timestamp is not even')
           ));
        }
        return $value; //this return is critical!
    }
}

并供参考 - post validator将在clean方法中获取表单的所有字段值数组作为$ value参数。