1

我有一个 SymfonyForm,它有 1:n embedForm(s)。主窗体和 embedForm 类有自己的 PreValidation,它实现了条件验证。EmbedForm 类的一部分如下所示:

private function configurePreValidators() {
    $validator = new sfValidatorCallback( array('callback'=> array($this, 'preValidation')) );
    $this->getValidatorSchema()->setPreValidator(new sfValidatorOr( array( $validator ) ));
}

public function preValidation(sfValidatorCallback $validator, array $values){
...
    $this->getValidator(self::SOME_FIELD)->setOption('required', false);
...
}
public function configure() {
    ...
    $this->configurePreValidators();
    parent::configure();
}

主窗体的预验证是类似的。

当我提交表单时,主表单预验证工作正常。

在 embed-Form 中,“SOME_FIELD”得到一个 required-validation-error,尽管我在 embedForm 的 preValidation 中将其显式设置为setOption('required', false)

在 embedForm 中使用预验证时有什么需要考虑的吗?那么mergePreValidator呢?有什么提示吗?

提前致谢!

4

1 回答 1

3

The issue here is not that your pre and post validators aren't firing -- they are (or at least, they should be). The issue is that the validator you are modifying is preValidate is not the one referenced in the top-level validator schema, i.e. the validator schema for the top-level form.

One solution: rather than modify the validator in preValidate, simply perform the validation:

public function preValidation(sfValidatorCallback $validator, array $values)
{
  if (!$this->getValidator(self::SOME_FIELD)->isEmpty($values[self::SOME_FIELD])
  {
    throw new sfValidatorErrorSchema(self::SOME_FIELD => new sfValdiatorError($validator, 'msg'));
  }
}

Note, this solution has some danger: if you modify the validator for SOME_FIELD inside of the top-level form, it will not be modified in this pre validator and vice-versa.

Let's look at why. In sfForm::embedForm:

public function embedForm($name, sfForm $form, $decorator = null)
{
  ...
  $this->validatorSchema[$name] = $form->getValidatorSchema();
  ...
}

Symfony simply nests the validators. This is why pre and post still get called. Why does the reference change? sfValidatorSchema::offsetSet:

public function offsetSet($name, $validator)
{
  ...    
  $this->fields[$name] = clone $validator;
}

So when a form is embedded, the validator schema is cloned. Thus, any modifications to the validators inside of an embedded form do not affect the top-level validator schema.

于 2010-12-09T19:45:03.837 回答