How do I send variables to an error layout in ZF3?

528 views Asked by At

What is right way to send variables to the layout templete for it be approachable in error pages?

I have AppFrontController above all my frontend controllers. It have code (code is near) in onDispatch() method:

 $assocArrayOfVars = $this->MyPlugin()->getDbVariablesArray();
  foreach($assocArrayOfVars as $name => $value){
     $this->layout()->$name = $value;
  }

  list($catalog, $count_goods) = $this->MyPlugin()->getStandardCatalogDataForLayout();
  $this->layout()->catalog = $catalog;
  $this->layout()->count_goods = $count_goods;

As the result, I have my local variables in every frontend page. But I have’nt it in an error page. How I can to deside this problem? I very need your advices! Thank you!

1

There are 1 answers

0
Илья Шах On

Thank you for your advices! Problem is solved. Code of final version Module.php file below. I use listener instead of a “parent controller” by froschdesign advice.

 public function onBootstrap(MvcEvent $event)
   {
      $application = $event->getApplication();
      $eventManager = $application->getEventManager();
      $eventManager->attach('dispatch', array($this, 'loadConfiguration'), 2);
      $eventManager->attach('dispatch.error', array($this, 'loadConfiguration'), 2);
}


 public function loadConfiguration(MvcEvent $e)
   {
      $application = $e->getApplication();
      $sm = $application->getServiceManager();
      $sharedManager = $application->getEventManager()->getSharedManager();

      $router = $sm->get('router');
      $request = $sm->get('request');

      $zendCart = $sm->get('ControllerPluginManager')->get('ZendCart');
      $myPlugin = $sm->get('ControllerPluginManager')->get('MyPlugin');
      $viewModel = $e->getViewModel();

      $viewModel->setVariable('total', $zendCart->total());
      $viewModel->setVariable('total_items', $zendCart->total_items());

      $viewModel->setVariable('rusmonth', $rusmonth);

      /* Layout variables */
      $assocArrayOfVars = $myPlugin->getDbVariablesArray();
      foreach ($assocArrayOfVars as $name => $value) {
         $viewModel->setVariable($name, $value);
      }

      list($catalog, $count_goods) = $myPlugin->getStandardCatalogDataForLayout();
      $viewModel->setVariable('catalog', $catalog);
      $viewModel->setVariable('count_goods', $count_goods);

   }

More listener examples here.