I want to create Categories menu from database records, but limit the menu items with current category and it's subcategories (like on Walmart.com). The catch is how to access current category in Navigation Factory where I create the pages for the menu?
Navigation factory:
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Navigation\Service\DefaultNavigationFactory;
class CategoriesMenu extends DefaultNavigationFactory
{
protected function getPages(ServiceLocatorInterface $serviceLocator)
{
if (null === $this->pages) {
$em = $serviceLocator->get('Doctrine\ORM\EntityManager');
// here I need to know the current category
$categories = $em->getRepository('Application\Entity\Category')->getRootCategories();
$nav = array();
foreach ($categories as $category) {
$page = array(
'label' => $category->getName(),
'route' => 'category',
'params' => array(
'category_path' => $category->getUrlName(),
),
'pages' => array(),
);
$nav[] = $page;
}
$configuration['navigation'][$this->getName()] = $nav;
$application = $serviceLocator->get('Application');
$routeMatch = $application->getMvcEvent()->getRouteMatch();
$router = $application->getMvcEvent()->getRouter();
$pages = $this->getPagesFromConfig($configuration['navigation'][$this->getName()]);
$this->pages = $this->injectComponents($pages, $routeMatch, $router);
}
return $this->pages;
}
}
Categories menu factory:
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Navigation\Service\DefaultNavigationFactory;
class CategoriesMenuFactory extends DefaultNavigationFactory
{
protected function getName()
{
return 'categoriesmenu';
}
public function createService(ServiceLocatorInterface $serviceLocator)
{
$navigation = new CategoriesMenu();
return $navigation->createService($serviceLocator);
}
}
module.config.php
'service_manager' => array(
'factories' => array(
'categoriesmenu' => 'Application\Navigation\Service\CategoriesMenuFactory',
),
),