ZF2表单中的按钮内容

时间:2014-02-14 10:32:32

标签: zend-framework2 zend-form zend-form-element

如何编辑Button元素(ZF2表单)的按钮内容? 我可以设置一个标签,但我想在其中插入一些HTML代码。

    $this->add(array(
        'type' => 'Button',
        'name' => 'submit',
        'options' => array(
            'label'   => 'Modifica',
        ),
        'attributes' => array(
            'type'  => 'submit',
            'class' => 'btn btn-warning'
        )
    ));

由于

3 个答案:

答案 0 :(得分:14)

您只需使用disable_html_escape标签选项即可。 它对我有用。

$this->add(array(
        'type' => 'Button',
        'name' => 'submit',
        'options' => array(
            'label' => '<i class="icon icon-foo"></i> Submit',
            'label_options' => array(
                'disable_html_escape' => true,
            )
        ),
        'attributes' => array(
            'type'  => 'submit',
            'class' => 'btn btn-success'
         )
    ));

答案 1 :(得分:5)

FormButton视图帮助器将自动转义按钮HTML内容,正如@Sam正确提到的那样。

避免这种情况的唯一方法是使用自定义表单按钮视图助手。而不是删除转义功能(因为按钮文本内容应该仍然被转义);你可以扩展视图助手并添加一个额外的选项,以允许你渲染html(我假设这是一个bootstrap图标)。

例如

use Zend\Form\View\Helper\FormButton as ZendFormButton;

class FormButton extends ZendFormButton
{

    public function render(ElementInterface $element, $buttonContent = null)
    {
        $content = (isset($buttonContent)) ? $buttonContent : $element->getLabel();
        $icon    = isset($element->getOption('icon')) ? $element->getOption('icon') : '';

        $escape = $this->getEscapeHtmlHelper();

        return $this->openTag($element) . $icon . $escape($content) . $this->closeTag();
    }

}

然后使用服务管理器中的按钮视图助手的默认注册名称('form_button')创建一个'invokable'配置条目。这将 然后意味着将使用我们的视图助手而不是默认的Zend\Form\View\Helper\FormButton

// Module.php
public function getViewHelperConfig()
{
    return array(
        'invokables' => array(
            'form_button' => 'MyModule\Form\View\Helper\FormButton',
        )
    );
} 

最后,更改按钮元素规范以添加新的“图标”选项

$this->add(array(
    'type' => 'Button',
    'name' => 'submit',
    'options' => array(
        'label'   => 'Modifica',
        'icon'    => '<i class="icon icon-foo">',
    ),
    'attributes' => array(
        'type'  => 'submit',
        'class' => 'btn btn-warning'
    )
));

其他一些观点

  • 如果您使用按钮的翻译,则上述代码将删除该功能;这可以很容易地再次添加(只需查看按钮视图助手)。我删除它以使示例更清晰
  • 您还可以对此进行扩展,以便为元素添加任意数量的其他选项(可能是按钮文本之前或之后的图标位置)。视图助手只需要读取此选项并输出正确的HTML。

答案 2 :(得分:3)

如果你需要的只是一个图标,使用css是一个更简单的选项,在表单文件中你只需要在你的按钮中添加一个自定义的css类,然后在你的样式表中使用之前的图标添加到类中像这样的内容:

$this->add(array(
        'type' => 'Button',
        'name' => 'submit',
        'options' => array(
            'label'   => 'Modifica',
        ),
        'attributes' => array(
            'type'  => 'submit',
            'class' => 'btn btn-warning custom-btn-with-icon'
        )
    ));

然后在css:

.custom-btn-with-icon:before {
    content: '\uxf005'; // this is the unicode of the custom-char you need for your icon
    font-family: 'fontAwesome'; // and this is the icon font of your project
}