I would like to know what other people think about having
Zend_Form_Element pass a $context to filters the same way it does for
validators. The specific case I'm working with involves a form with a
textarea element that can toggle between rich or plain text entry.
Depending on which is selected, the form has a hidden "format" element
whose value is either 'text/plain' or 'text/html'.
I have written a custom filter that strips out extra markup from
people who paste from Microsoft Word (in case some slips past the
filters built into the rich text element) as well as limiting the
input to only the elements and attributes I want it to allow.
(StripTags didn't do quite what I needed.) I would like to apply this
filter along with either Zend_Filter_StripTags or
Zend_Filter_HtmlEntities, but obviously I don't want them all applied
at the same time. If the form element passed the same $context to
filters that it currently passes to validators, it would allow
something like this:
class My_Filter_ConditionalStripTags extends Zend_Filter_StripTags
{
public function filter($value, $context = null)
{
if (is_array($context)) {
if (array_key_exists('format', $context) &&
$context['format'] == 'text/plain') {
return parent::filter($value, $context);
}
}
return $value;
}
}
class My_Filter_ConditionalCleanHtml extends Zend_Filter_Abstract
{
public function filter($value, $context = null)
{
if (is_array($context)) {
if (array_key_exists('format', $context) &&
$context['format'] == 'text/html') {
/* ... apply filter ... */
return $filtered;
}
}
return $value;
}
}
As a workaround for now, I've added a protected property $_enabled to
my custom filter class, and I have the controller set its value
depending on the value of $request->getPost('format') before calling
isValid() on the form. If the filter is enabled, it runs; otherwise it
just returns the original input value. It works, but I would prefer to
have the logic encapsulated internally.
Is this something others would find useful?
Andrew