How to put a character entity in the value of a fo

2019-08-14 03:21发布

问题:

When I create a submit button in a ZF2 form like this:

    $this->add(array(
            'name' => 'save_closebutton',
            'attributes' => array(
                    'type'  => 'submit',
                    'value' => 'Save & Move On »',
                    'id'    => 'save_closebutton',
                    'class' => 'btn btn-default'
            ),
    ));

and then put a formSubmit element in the view like this:

    echo $this->formSubmit($form->get('save_closebutton'));

ZF2 renders the text in the button as Save & Move On » without rendering the character that the code represents.

I'm pretty sure that the problem is in the formSubmit helper, because inspecting the element shows that the helper creates this:

    <input id="save_closebutton" class="btn btn-default" type="submit" value="Save & Move On &#187;" name="save_closebutton">

but if I simply echo the same string in the view,

    echo '<input id="save_closebutton" class="btn btn-default" type="submit" value="Save & Move On &#187;" name="save_closebutton">';

the button is rendered correctly.

How do I get formSubmit to pass the character and not the code?

回答1:

The FormSubmit helper escapes attribute names and values before output, AFAIK there's no way to disable that without providing custom helpers.

Since your submit element is just a button, you can use the Button element and the FormButton view helper to solve your problem. The element has a label option which allows you to disable html escaping on the label, and the helper respects that setting.

Create your submit button in the form ...

$this->add(array(
        'name' => 'save_closebutton',
        'type' => 'Button', // \Zend\Form\Element\Button
        'options' => array(
             'label' => 'Save & Move On &#187;',
             // inform the FormButton helper that it shouldn't escape the label
             'label_options' => array(
                  'disable_html_escape' => true,
             ),
        ),
        'attributes' => array(
            'type'  => 'submit',  // <button type="submit" .../>
            'id'    => 'save_closebutton',
            'class' => 'btn btn-default'
        ),
));

Use the FormButton helper to render the element ...

 echo $this->formButton($form->get('save_closebutton'));