ZF2视图助手配置


ZF2 View helpers configuration

我正在学习Zend框架2,我正试图改变表单视图助手的配置。每个都有重新配置主题变量的方法,例如FormCollection helper有$wrapper变量和setter/getter。像Flashmessenger的配置(在文档中描述)一样,我在module.config.php中创建了config:

'view_helper_config' => array(
    'flashmessenger' => array(
        'message_open_format'      => '<div%s><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><ul><li>',
        'message_close_string'     => '</li></ul></div>',
        'message_separator_string' => '</li><li>'
    ),
    'formcollection' => array(
        'wrapper' => '<fieldset%4$s>TEEST %2$s%1$s%3$s</fieldset>',
        'label_wrapper' => 'TEST <legend>%s</legend>',
    ),

这行不通

——编辑:

我刚刚发现,view_helper_config只在FlashMessengerFactory服务中使用。所以用这种方式配置视图助手是不可能的。也许有人有其他建议?

我发现最好的方法(目前)是覆盖现有的帮助。formCollection的例子中,我的module。config。php:

'view_helpers' => array(
    'invokables' => array(
        'formCollection' => 'MyLibrary'View'Helper'FormCollection',
    ),

MyLibrary当然是任何你想要的命名空间。在我的视图帮助器中,只有几个变量被重写:

namespace MyLibrary'View'Helper;
use Zend'Form'ElementInterface;
use Zend'Form'View'Helper'FormCollection as BaseFormCollection;
class FormCollection extends BaseFormCollection {
    /**
     * This is the default wrapper that the collection is wrapped into
     *
     * @var string
     */
    protected $wrapper = '<fieldset%4$s>TEST %2$s%1$s%3$s</fieldset>';
    /**
     * This is the default label-wrapper
     *
     * @var string
     */
    protected $labelWrapper = '<legend>TEST 2 %s</legend>';        
}

用法与之前相同,因为在配置可调用项中我使用了相同的名称:formCollection。

我不确定那是不是最好的方法。但它快速、容易做到,而且很容易完全重写helper方法(例如render())。顺便说一下,在我看来是唯一的办法。当然,我们可以在使用之前使用辅助方法,例如,view script:
$this->formCollection()->setWrapper('new wrapper');
// now its use new wrapper
echo $this->formCollection('collection');