2013-12-20 73 views
0

我使用Zend \ Form \ Element \ Collection動態添加'行'。這工作正常,但我努力爲這些行添加驗證。驗證Zend Form Element Collection

到目前爲止,我的代碼看起來如下所示。我相信我需要的東西傳遞給InputFilter輸入\輸入過濾::加(),但我想不出什麼:

<?php 

class EditForm extends \Zend\Form\Form 
{ 
    public function __construct() 
    { 
     parent::__construct('edit'); 
     $this->setUpFormElements(); 
     $this->setupInputFilters(); 
    } 

    protected function setUpFormElements() 
    { 
     $fieldset = new \Zend\Form\Fieldset; 

     $nameElement = new \Zend\Form\Element\Text('name'); 
     $fieldset->add($nameElement); 

     $descriptionElement = new \Zend\Form\Element\Text('description'); 
     $fieldset->add($description); 

     $this->add(
      array(
       'type' => 'Zend\Form\Element\Collection', 
       'name' => 'rows', 
       'options' => array(
        'label' => 'Edit Rows', 
        'should_create_template' => true, 
        'allow_add' => true, 
        'target_element' => $fieldset, 
       ) 
      ) 
     ); 

     return $this; 
    } 

    public function setupInputFilters() 
    { 
     $filter = new \Zend\InputFilter\InputFilter(); 

     $filter->add(
      array(
       'name' => 'rows', 
       'required' => true, 
       'validators' => array(
        // Not sure what to do here! 
       ) 
      ) 
     ); 

     return $this; 
    } 
} 

回答

0

我認爲你需要輸入過濾器添加到您的字段集的getInputFilterSpecification方法動態添加

class Row extends Fieldset implements InputFilterProviderInterface 
{ 

     $this->add(array(
      'name' => 'yourFieldset', 
      'options' => array(
       'label' => 'One of your fieldset elements' 
      ), 
      'attributes' => array(
       'required' => 'required' 
      ) 
     )); 


     $this->add(array(
      'name' => 'fields', 
      'options' => array(
       'label' => 'Another fieldset element' 
      ), 
      'attributes' => array(
       'required' => 'required' 
      ) 
     )); 

     public function getInputFilterSpecification() 
     { 
      return array(
       'yourFieldset' => array(
        'required' => true, 
       ), 
       'fields' => array(
        'required' => true, 
        'validators' => array(
         array(
          'name' => 'Float' 
         ) 
        ) 
       ) 
      ); 
     }  

然後在您的形式,你需要設置驗證組

class EditForm extends Form 
{ 
    public function __construct() 
    { 
     $this->add(
     array(
      'type' => 'Zend\Form\Element\Collection', 
      'name' => 'rows', 
      'options' => array(
       'label' => 'Edit Rows', 
       'should_create_template' => true, 
       'allow_add' => true, 
       'target_element' => $fieldset, 
      ) 
      ) 
     ); 

     $this->setValidationGroup(array(
      'csrf', 
      'row' => array(
       'yourFieldset', 
       'fields', 
      ) 
     )); 
    } 
}