0
votes

I have a form with an input type='text' name='article[]' . I don't know the number of article that can be post because there is a little javascript button where I can add as much I want input name=article[].

For now, I use Zend\InputFilter\InputFilter but the validators never get the value on the array in my $_POST.

My input : 
<input name="article[]" class="form-control input-md" type="text" >         


My InputFilter :
class ArticleFormFilter extends InputFilter{
    public function __construct()    {

    $this->add(array(
            'name'       => 'article[]',
            'required'   => true,
            'filters' => array(
                array(
                    'name'    => 'Zend\Filter\StripTags',
                ),
                array(
                    'name'    => 'Zend\Filter\StringTrim',
                ),
            ),
            'validators' => array(
                array(
                    'name' => 'NotEmpty',                       
                ),
            ),            
        ));
    }
}

If I do it with only one article, using article instead of article[] and no Javascript, it works of course.

2

2 Answers

2
votes

To validate and/or filter arrays of POST data use CollectionInputFilter:

class MagazineInputFilter extends \Zend\InputFilter\InputFilter
{
    public function __construct()
    {            
        $this->add(new \Zend\InputFilter\Input('title'));        
        $this->add(new ArticlesCollectionInputFilter(), 'articles');
    }
}

class ArticlesCollectionInputFilter extends \Zend\InputFilter\CollectionInputFilter
{
    public function __construct()
    {
        // input filter used for each article validation. 
        // see source code of isValid() method of this class
        $inputFilter = new \Zend\InputFilter\InputFilter();

        /* 
        add inputs and its validation/filtration chains
        */

        $this->setInputFilter($inputFilter);
    }
}

Or setup input filter for collection inside main input filter of magazine:

class MagazineInputFilter extends \Zend\InputFilter\InputFilter
{
    public function __construct()
    {
        $articles = new \Zend\InputFilter\CollectionInputFilter();
        $articlesInputFilter = new \Zend\InputFilter\InputFilter();
        /*
        add inputs and its validation/filtration chains
         */
        $articles->setInputFilter($articlesInputFilter);

        $this->add(new \Zend\InputFilter\Input('title'));        
        $this->add($articles, 'articles');
    }
}
0
votes

first of all the field name shoud be "article" not "article[]".

When you change it you will find another problem:

Warning: Zend\Filter\StripTags::filter expects parameter to be scalar, "array" given; cannot filter

AFAIK the Zend 2 filters doesn't work with arrays... Some answers are here: Zend Framework 2 filter / validate array of contents