Zend_Form and setElementFilters with Zend_Filter_StringTrim does not trim

1.4k Views Asked by At

PHP Code:

$form = new Zend_Form();
$filters = array(new Zend_Filter_StringTrim());
$form->setElementFilters($filters); // <-- ISSUE

$customerName = new Zend_Form_Element_Text('customer_name');
$customerName->setRequired();
$form->addElement($customerName);

$data = $this->_getAllParams();
if ($form->isValid($data)) {
    var_dump($form->getValue('customer_name'));
    // Should be "Testing Trim"
    // Actual result is " Testing Trim "
} else {
    exit('Failed');
}

HTML Code:

<form action="" method="post">
    <input type="text" name="customer_name" value=" Testing Trim " />
    <input type="submit" />
</form>

Has anyone come across this issue and if so how do you fix it globaly for the setElementFilters method?

If I add the filter to the element it works fine. I just don't want to set the trim for each element.

2

There are 2 best solutions below

1
On BEST ANSWER

I believe the problem is that you're setting filters before the element has actually been added to the form. Try changing the order, first add the element, then set filters:

$form->addElement($customerName);    
$form->setElementFilters($filters);
1
On

Try this

 $form->setElementFilters(array('StringTrim'));