Search code examples
phpformszend-frameworkzend-framework2escaping

Diasble escaping in Zend 2 Forms


It seems that in some cases, allowing the attributes of a form element to be set without escaping might come in handy. Examples are assignment of multiple classes via

class="class1 class2"

or the use of bootstrap validation for matching fields, which requires the attribute

data-match="#field1"

on field2 in order to check whether field1 and field2 have the same content.

Both the spaces and the hash sign will be escaped by the ZF2 form creation mechanism if I create them like this:

   $this->add(array(
        'name' => 'field2',
        'type' => 'text',
        'attributes' => array(
            'data-match' => '#field1'
        )
    ));

I have done quite a bit of searching on this and found nothing so far (except for one or two obsolete answers pertaining to ZF1). A cursory look at ZF2's source code further suggested that it might indeed not be possible at all to disable escaping, leaving no straightforward way to accomplish what I want. But I find this hard to imagine and still prefer to believe that I suck at searching and PHP. Which is correct?


Solution

  • As someone kindly pointed out to me on twitter, data-match and apparently also separating classes also work with escaped spaces/hashes. This didn't occur to me since I did not expect it and my code was not working properly for extraneous reasons. But given this fact, the escaper can of course be used universally without causing the problem described.