Zned 2如何覆盖FormElementErrors

时间:2015-05-16 07:53:14

标签: zend-framework2

我想覆盖全局这些变量:

\ Zend的\表格\视图\助手\ FormElementErrors.php 形式:

protected $messageCloseString     = '</li></ul>';
protected $messageOpenFormat      = '<ul%s><li>';
protected $messageSeparatorString = '</li><li>';

要:

protected $messageCloseString     = '</li></ul>';
protected $messageOpenFormat      = '<ul%s><li class="errors">';
protected $messageSeparatorString = '</li><li>';

我该怎么做? 感谢名单!

3 个答案:

答案 0 :(得分:2)

如果您希望全局设置,可以为此(或任何其他)视图助手创建自己的工厂:

<?php

namespace Application\Factory\Form\View\Helper;

use Zend\Form\View\Helper\FormElementErrors;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class FormElementErrorsFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $helper = new FormElementErrors();
        $helper->setMessageOpenFormat('<ul%s><li class="errors">');

        return $helper;
    }
}

并覆盖ViewHelperManager的配置:

<?php
// module.config.php

return [
    'view_helpers' => [
        'factories' => [
            'formelementerrors' => \Application\Factory\Form\View\Helper\FormElementErrorsFactory::class,
        ],
    ],
];

现在您可以像往常一样使用formElementErrors查看帮助程序,但使用自定义配置。

答案 1 :(得分:1)

您可以通过在您的视图文件顶部调用此帮助程序中的setter来设置邮件格式的任何部分:

<?php
$this->formElementErrors()
    ->setMessageOpenFormat('<p class="help-block">')
    ->setMessageSeparatorString('</p><p class="help-block">')
    ->setMessageCloseString('</p>');

TW Bootstrap的示例格式错误消息。

答案 2 :(得分:0)

日Thnx! Awnser 1 en 2合并,给出:

namespace Application\Factory\Form\View\Helper;

use Zend\Form\View\Helper\FormElementErrors;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class FormElementErrorsFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
    $helper = new FormElementErrors();
    $helper->setMessageOpenFormat('<ul%s><li class="errors">');

    return $helper;
}
}

//module.config

'view_helpers' => array(
'invokables'=> array(
    'formelementerror' => '\Admin\Factory\Form\View\Helper\FormElementErrorsFactory'
)
),

//view.phtml
$element = $this->formElementErrors()
->setMessageOpenFormat('<p class="help-block">')
->setMessageSeparatorString('</p><p class="help-block">')
->setMessageCloseString('</p>');
foreach ($form as $element) {        
echo '<div class="form-group">
    <div class="input-group">';
echo $this->formElement($element);
echo '</div></div>';
echo $this->formElementErrors($element);
}
echo $this->form()->closeTag();?>