I'm trying to determine the current request in a view helper for zend framework 2. the purpose is to add the class active
to the navigation element. Here is my current code:
<li class="active"><a href="<?php echo $this->url('home') ?>"><?php echo $this->translate('Home') ?></a></li>
<li><a href="<?php echo $this->url('companies'); ?>"><?php echo $this->translate('Companies') ?></a>
<li><a href="<?php echo $this->url('contacts'); ?>"><?php echo $this->translate('Contacts') ?></a>
<li><a href="<?php echo $this->url('tasks'); ?>"><?php echo $this->translate('Tasks') ?></a>
<li><a href="<?php echo $this->url('projects'); ?>"><?php echo $this->translate('Projects') ?></a>
<li><a href="<?php echo $this->url('reports'); ?>"><?php echo $this->translate('Reports') ?></a>
<li><a href="<?php echo $this->url('logout'); ?>"><?php echo $this->translate('Logout') ?></a>
As you can see, currently the home anchor is set to active.
My intentions are to do the following, per say:
<li <?php echo $this->active('companies');?>
As you can see, I'm going to create a custom view helper called active
that passes the companies module to the view helper. In the view helper, i need to access the request and ensure for this example the module is companies
. So, any requests that use the company module would strategically set that navigation li element as active.
So really my question is how do i access the current module in the request in a custom view helper.
Here is the solution:
<?php
namespace Sam\View\Helper;
use Zend\View\Helper\AbstractHelper;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
class Active extends AbstractHelper implements ServiceLocatorAwareInterface
{
protected $activemodule;
use \Zend\ServiceManager\ServiceLocatorAwareTrait;
public function __invoke($module)
{
if($this->getRouteName() === $module){
return 'class="active"';
}
return null;
}
public function getRouteName()
{
if (!$this->activemodule){
$routeMatch = $this->getServiceLocator()->getServiceLocator()->get('Application')->getMvcEvent()->getRouteMatch();
$this->activemodule = $routeMatch->getMatchedRouteName();
}
return $this->activemodule;
}
}