How to use a custom form view helper in Zend Framework 2?
Asked Answered
Z

2

5

I wrote a form view helper, that extends the Zend\Form\View\Helper\FormMultiCheckbox and overwrites its renderOptions(...) method:

<?php
namespace MyNamespace\Form\View\Helper;

use Zend\Form\View\Helper\FormMultiCheckbox as ZendFormMultiCheckbox;

class FormMultiCheckbox extends ZendFormMultiCheckbox 
{

    protected function renderOptions(...)
    {
        ...
        $label     = $escapeHtmlHelper($label);
        $labelOpen = $labelHelper->openTag($labelAttributes);
        switch ($labelPosition) {
            case self::LABEL_PREPEND:
                $template  = $labelOpen . $label . $labelClose . '%s';
                break;
            case self::LABEL_APPEND:
            default:
                $template  = '%s' . $labelOpen . $label . $labelClose;
                break;
        }
        $markup = sprintf($template, $input);

        $combinedMarkup[] = $markup;
        ...
    }

}

The next step is to register the new view helper. I'm doing this like here shown:

namespace Application;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module {

    ...

    public function getViewHelperConfig() {
        return array(
            'invokables' => array(
                'FormMultiCheckboxViewHelper' => 'MyNamespace\Form\View\Helper\FormMultiCheckbox',
            )
        );
    }
}

Now my question: How can I make the application use my form view helper instead of Zend\Form\View\Helper\FormMultiCheckbox?

Zante answered 10/4, 2013 at 21:31 Comment(0)
U
10

Although Andrews answer works, it's not necessary, just use the default view helper name and map it to your helper class, the application will then use your helper instead

public function getViewHelperConfig() {
    return array(
        'invokables' => array(
            'formmulticheckbox' => 'MyNamespace\Form\View\Helper\FormMultiCheckbox',
        ),                
    );
}
Utham answered 11/4, 2013 at 3:36 Comment(0)
T
-1

here's an example of overriding a view helper:

http://ctrl-f5.net/php/zf2-servicemanager-custom-viewhelpers/


Example:

class Module {

    public function onBootstrap(MvcEvent $mvcEvent)
    {
        $application = $mvcEvent->getApplication();
        $serviceManager = $application->getServiceManager();
        $viewHelperManager = $serviceManager->get('ViewHelperManager');
        $viewHelperManager->setInvokableClass('formmulticheckbox', 'MyNamespace\Form\View\Helper\FormMultiCheckbox');
    }
    ...
}
Tatianna answered 10/4, 2013 at 22:7 Comment(1)
This should not be done that way. You should use Crisp's answer (below) to get this done right.Abuse

© 2022 - 2024 — McMap. All rights reserved.