Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple PregReplace filters on a Zend Form element

I want to be able to add multiple PregReplace filters on a single Zend Form element. I can add one PregReplace filter using the code below:

$word = new Zend_Form_Element_Text('word');
$word->addFilter('PregReplace', array(
        'match' => '/bob/', 
        'replace' => 'john'
    ));
$this->addElement($word);

I've tried

$word = new Zend_Form_Element_Text('word');
$word->addFilter('PregReplace', array(
        'match' => '/bob/', 
        'replace' => 'john'
    ));
$word->addFilter('PregReplace', array(
        'match' => '/sam/', 
        'replace' => 'dave'
    ));
$this->addElement($word);    

but this just meant only the second filter worked.

How do I add multiple PregReplace filters?

like image 817
AndySidd Avatar asked Jul 15 '11 10:07

AndySidd


2 Answers

The problem you're facing is that the second filter will override the first one in the filters stack ($this->_filters) defined in Zend_Form_Element.

As David mentioned in the question comments, the filters stack use filter names as index ($this->_filters[$name] = $filter;) this is the reason why the second filter override the first one.

In order to resolve this problem, you can use a custom filter as follows:

$element->addFilter('callback', function($v) { return preg_replace(array('/bob/', '/sam/'),array('john', 'dave'), $v); });

This is done using an inline function(), in case you're not using PHP version 5.3 or higher, you can set your callback as follows to make it work:

$element->addFilter('callback', array('callback' => array($this, 'funcName')));

And add under your init() method in your form:

function funcName($v) {
    return preg_replace(array('/bob/', '/sam/'), array('john', 'dave'), $v);
}

At last, if you want to use only the PregReplace filter, unlike Marcin's answer (the syntax is incorrect), you can still do it this way:

$element->addFilter('pregReplace', array(
          array('match' => array('/bob/', '/sam/'),
                'replace' => array('john', 'dave')
)));

That should do the trick ;)

like image 191
Liyali Avatar answered Oct 11 '22 23:10

Liyali


Since PregReplace uses php's preg_replace function, I guess something like this would be possible (preg_replace can accepts arrays of patterns and array of corresponding replacement strings):

$word = new Zend_Form_Element_Text('word');
$word->addFilter('PregReplace', array(
        'match'   => array('/bob/', '/sam/'), 
        'replace' => array('john' ,  dave)
    ));
$this->addElement($word);

I haven't tested it though. Hope it will work.

like image 37
Marcin Avatar answered Oct 12 '22 01:10

Marcin