在ZF2中在表单级别添加验证的正确方法是什么?

时间:2016-08-23 09:53:46

标签: validation zend-framework2 zend-form zend-form-element zend-form-fieldset

有一个包含大量嵌套字段集的复杂表单。某些字段需要根据另一个字段集中的字段(-s)进行验证。所以我无法直接在getInputFilterSpecification()的{​​{1}}中定义所有验证规则,因为我无法访问其他字段集(只有子字段集)。唯一的方法是扩展Fieldset验证。对?如果是这样,怎么做?

Form

喜欢这个?或者是一种更清洁的方法来解决这个问题?

1 个答案:

答案 0 :(得分:0)

我已经在之前的项目中开发了类似的东西。

为此,我使用了一个服务,它接受我的表单并设置动态字段集,显然还有自定义验证规则。

在你的控制器中,获取你的表格(通过依赖注入formManager(polyfilled or not)。

$form = $this->formManager->get('{your form}');

致电您的服务并提供表格。

在您的服务中,您可以做任何您想做的事情:

  • 获取您的资料(来自数据库或其他人)以确定哪些字段是必填字段
  • Foreach on your form
  • 添加或删除字段集
  • 添加或删除validationGroup字段
  • 添加或删除过滤器
  • 添加或删除验证器

我通过(样本)在foreach中执行了那些$stuff是教义集合的元素

$nameFieldset = 'my_fieldset-'.$stuff->getId();
            $globalValidator = new GlobalValidator();
            $globalValidator->setGlobalValue($gloablValue);

            $uoValidator = new UcValidator();
            $uoValidator->setOptions(array(
                'idToValidate' => $stuff->getId(),
                'translator' => $this->translator
            ));

            $globalValidator->setOptions(array(
                'idToValidate' => $stuff->getId(),
                'translator' => $this->translator
            ));

            $name = 'qty-'.$stuff->getId();

            $form = $this->setFilters($form, $name, $nameFieldset);
            $globalValidator->setData($data);
            $form = $this->setValidators($form, $name, $globalValidator, $uoValidator, $nameFieldset);

其中setFilters和setValidators是自定义方法,它们为我的字段添加过滤器和验证器(也是自定义的)

/**
 * @param myForm $form
 * @param $name
 * @param string $nameFieldset
 * @return myForm
 */
public function setFilters($form, $name, $nameFieldset)
{
    $form->getInputFilter()->get('items')->get($nameFieldset)
        ->get($name)
        ->getFilterChain()
        ->getFilters()
        ->insert(new StripTags())
        ->insert(new StringTrim());

    return $form;
}


/**
 * @param myForm $form
 * @param $name
 * @param $globalValidator
 * @param $uoValidator
 * @param $nameFieldset
 * @return myForm
 */
public function setValidators($form, $name, $globalValidator, $uoValidator, $nameFieldset)
{
    $optionsSpace = [
        'translator' => $this->translator,
        'type' => NotEmpty::SPACE
    ];
    $optionsString = [
        'translator' => $this->translator,
        'type' => NotEmpty::STRING
    ];
    $optionsDigits = [
        'translator' => $this->translator,
    ];
    $form->getInputFilter()->get('items')
        ->get($nameFieldset)
        ->get($name)
        ->setRequired(true)
        ->getValidatorChain()
        ->attach($uoValidator, true, 1)
        ->attach($globalValidator, true, 1)
        // We authorize zéro but not space nor strings
        ->attach(new NotEmpty($optionsSpace), true, 2)
        ->attach(new NotEmpty($optionsString), true, 2)
        ->attach(new Digits($optionsDigits), true, 2);
    return $form;
}