2014-02-26 20 views
1

是否可以将完整的表单作为上下文传递给验证器?使用Fieldset或Collection时的ZF2验证器上下文

我想创建用于在字段集A元素X条件验证器,其检查在不同的字段集B.元件Y的值

的问题是,所述的isValid功能仅接收用于字段集的上下文中是这个元素X对元素Y一无所知。

所有答案大大收到!

回答

2

你可以使用集合和ZendCollectionInputFilter是的。

这里没有像本文档的负荷,知道了Zend家伙了,虽然排序此(认为唯一一提的是在http://framework.zend.com/apidoc/2.2/classes/Zend.InputFilter.CollectionInputFilter.html),但现在的资源,真正帮助我是这样的:

http://www.aronkerr.com/2013/11/zf2-form-collection-validation-unique.html

很聪明的东西,一旦你把你的头围绕这些。由于您的问题并不具体,您的表单,代码字段和输入过滤器没有任何代码,您现在已经使用过,但希望这有助于您。如果您在任何时候遇到困难,都乐于运行更具体的代码

+0

谢谢@Jon - 该指南正是我所需要的 –

0

假设我们的字段集A和B属于Sample的形式。我们需要从这个父窗体,以访问这种形式的情况下添加验证验证任何孩子的fieldsets时:

<?php 

namespace App\Form; 

use Zend\Form\Form; 
use Zend\InputFilter\InputFilterProviderInterface; 

class Sample extends Form InputFilterProviderInterface 
{ 
    public function init() 
    { 
     $this->add([ 
      'type' => 'App:Fieldset:A', 
      'name' => 'fieldsetA', 
     ]); 

     $this->add([ 
      'type' => 'App:Fieldset:B', 
      'name' => 'fieldsetB', 
     ]); 

     $this->add([ 
      'type' => 'submit', 
      'name' => 'submit', 

      'attributes' => [ 
       'value' => 'Submit', 
      ], 
     ]); 
    } 

    public function getInputFilterSpecification() 
    { 
     return [ 
      'fieldsetA' => [ 
       'type' => 'InputFilter', 

       'X' => [ 
        'required' => true, 
        'allow_empty' => true, 
        'continue_if_empty' => true, 

        'validators' => [ 
         [ 
          'name' => 'Callback', 
          'options' => [ 
           'callback' => function ($value) 
           { 
            if ($this->data['fieldsetB']['Y']) 
            { 
             // do something 
            } 
            // do something else 
           }, 
          ], 
         ], 
        ], 
       ], 
      ], 
     ]; 
    } 
} 

注意如何我们在一个从内Sample使用InputFilter类型添加验证器X。接下来我们直接访问$this->data并遍历它以得到Y中的Y.