Search code examples
formslayoutzend-framework2

ZF2 How to set search form in layout


What is the right way to set a (search) form with Zend Framework 2 in the layout.ptml who is visible on any page of the website?

Thanks in advance.

Nick


Solution

  • It is really simple to set any variables to all layouts in ZF2 by EventManager, just attach the EVENT_RENDER event such as:

    class Module
    {
        public function onBootstrap($e)
        {
            $app = $e->getParam('application');
            $app->getEventManager()->attach(MvcEvent::EVENT_RENDER, array($this, 'setFormToView'), 100);
        }
    
        public function setFormToView($event)
        {
            $form = new MyForm();
            $viewModel = $event->getViewModel();
            $viewModel->setVariables(array(
                'form' => $form,
            ));
        }
    }