Search code examples
phpzend-framework2

Zend Framework 2 filter / validate array of contents


How do I apply a filter to a field element with the contents of an array?

For example:

$this->add(
  "name" => "tags",
  "type" => "text",
  "filter" => array(
    array("name" => "StripTags"),
    array("name" => "StringTrim")
  )
);

$tags[0] = "PHP";
$tags[1] = "CSS";

If I attempt to filter I receive an error saying a scalar object is excepted, array given.


Solution

  • This isn't really possible at this time. Your best bet is to use a Callback filter and filter each Item individually. Something like this

    $this->add(
      "name" => "tags",
      "type" => "text",
      "filter" => array(
        array("name" => "Callback", "options" => array(
           "callback" => function($tags) {
              $strip = new \Zend\Filter\StripTags();
              $trim = new \Zend\Filter\StringTrim();
              foreach($tags as $key => $tag) {
                $tag = $strip->filter($tag);
                $tag = $trim->filter($tag);
                $tags[$key] = $tag;
              }
              return $tags;
        }))
      )
    );