简体   繁体   中英

ZF2 View helpers configuration

I am learning Zend Framework 2 and i'm trying to change form view helpers configuration. Each has methods to reconfigure theme variables, for examples FormCollection helper have $wrapper variable and setters/getters. Like for Flashmessenger configuration (described in documentation) i created config inside module.config.php:

'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>',
    ),

This doesn't work

---- edit:

I just discovered, that view_helper_config is used only inside service FlashMessengerFactory. So its impossible to configure view helpers this way. Maybe somebody have other suggestions?

Best way (for now) i found is to override existing helper. So by the example of formCollection, my module.config.php:

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

Where MyLibrary is of course any namespace you want. Inside my view helper, there are only few variables overrided:

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>';        

}

Usage is the same like before, because inside configuration invokables i used same name: formCollection.

Im not sure that is the best way to do it. But its fast, easy to do, and its easy to override helper methods totally (for example render()). By the way, in my opinion is the only way. We can of course use helper methods before use, for example, view script:

$this->formCollection()->setWrapper('new wrapper');
// now its use new wrapper
echo $this->formCollection('collection');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM