Zend_Form: remove default filter from one element
I extended Zend_Form with my own class and let inherit all my forms from that. My base-class applies a default filter to all 开发者_C百科form elements that strips out double whitespaces, basically:
return trim(preg_replace('/\s+/', ' ', $value));
While usually i want this on every element, there are some occasions where it breaks stuff, for example on textareas (newlines get removed aswell) so i'm looking for a way to disable that default filter on certain elements. I tried this (unsuccessfully):
$element->clearFilters();
however within the forms init() method that filter is not yet set ($element->getFilters() returns an empty array), only when calling methods like __toString() or isValid() it gets applied, but I'd rather not overwrite those methods just to get rid of the filter. There must be a better way?!
The cleanest solution would probably be to opt-in that filter and not apply by default - but I'd rather keep it default and find a way to exclude certain elements.
skooli, the OP, already self-answered the question:
Quote:
Resolved!
The setElementFilters()
method will run over all elements currently added to the form and apply the filter, so now I've just overwritten that method to work like this:
public function setElementFilters(array $filters) {
foreach ($this->getElements() as $element) {
if(!($element instanceof Zend_Form_Element_Textarea)) {
$element->setFilters($filters);
}
}
return $this;
}
While this will work with all textareas I cant exclude arbitrary fields of other types. Should I need that I'll probably create a dummy filter that does nothing but can be used to determine whether the fixWhitespaces
filter should be omitted.
Note: It's absolutely OK to self-answer your own question. Please just post it as an real answer, but not in a question or comment. Posting as real answer helps to keep the "Unanswered" list more clear (avoids making other people wasting their time).
精彩评论