Php 在操作Symfony中抛出新的SFValidator错误
我通过简单的行动产生了:Php 在操作Symfony中抛出新的SFValidator错误,php,symfony1,symfony-1.4,Php,Symfony1,Symfony 1.4,我通过简单的行动产生了: protected function processForm(sfWebRequest $request, sfForm $form) { $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName())); if ($form->isValid()) { $test = $for
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());
}
}
是否可以为此错误添加?
例如:
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中是否可能实现这一点?我猜您只是想添加新的验证器,而不是抛出sfValidator错误(特别是sfValidator错误必须引用抛出它的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!
}
}
然后:将验证器添加到表单中(但最好使用forms configure方法):
然后,您可以通过调用
//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参数的形式获取表单中所有字段值的数组。请详细说明您正在尝试执行的操作。
//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!
}
}