symfony1 - Symfony 1.4 动态验证可能吗?

标签 symfony1 symfony-1.4 symfony-forms

我正在尝试创建一个表单,该表单根据 html 表单字段中的选择选项来更改字段的验证。

例如:如果用户从下拉字段“选项”中选择选项 1,我希望字段“指标”验证为 sfValidatorInteger。如果用户从“选项”字段中选择选项 2,我希望“指标”字段验证为 sfValidatorEmail 等。

因此,在 public function configure() { 中,我有 switch 语句来捕获“options”的值,并根据从“options”返回的值创建验证器。

1.) 如何捕获“选项”的值?我试过:

$this->getObject()->options
$this->getTaintedValues()

目前唯一对我有用的是,但它并不是真正的 MVC:

$params = sfcontext::getInstance()->getRequest()->getParameter('options');

2.) 捕获该信息后,如何将“metric”的值分配给不同的字段? (“metric”不是数据库中的真实列)。所以我需要将“metric”的值分配给不同的字段,例如“email”,“age”......目前我正在像这样的帖子验证器中处理这个问题,只是想知道我是否可以在配置中分配值( ):

$this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'checkMetric'))));

public function checkMetric($validator, $values) {

}

谢谢!

最佳答案

您想要使用帖子验证器。尝试在您的表单中执行以下操作:

public function configure()
{
  $choices = array('email', 'integer');
  $this->setWidget('option', new sfWidgetFormChoice(array('choices' => $choices))); //option determines how field "dynamic_validation" is validated
  $this->setValidator('option', new sfValidatorChoice(array('choices' => array_keys($choices)));
  $this->setValidator('dynamic_validation', new sfValidatorPass()); //we're doing validation in the post validator
  $this->mergePostValidator(new sfValidatorCallback(array(
    'callback' => array($this, 'postValidatorCallback')
  )));
}

public function postValidatorCallback($validator, $values, $arguments)
{
   if ($values['option'] == 'email')
   {
     $validator = new sfValidatorEmail();
   }
   else //we know it's one of email or integer at this point because it was already validated
   {
     $validator = new sfValidatorInteger();
   }
   $values['dynamic_validation'] = $validator->clean($values['dynamic_validation']); //clean will throw exception if not valid
   return $values;
}

关于symfony1 - Symfony 1.4 动态验证可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3611450/

相关文章:

php - 前端后端的 url_for - Symfony

mysql - Symfony 1.4 更改 AdminGenerator-module/Find Query 中的嵌入表单

exception - symfony 1.4 : How to pass exception message to error. html.php?

php - 交响乐 : error while accessing an array

php - 在 Symfony 中使用 PHP 简单 HTML DOM 解析器时出错

php - Symfony 忽略 web/中的目录

unit-testing - Symfony 单元测试不会加载 app_ globals

php - 可以在 PHP7 下运行 symfony 1.4 吗?

css - 将内联样式添加到 symfony2 Twig 形式

symfony - 非映射表单、Ent​​ityType 和数据属性