I have an issue since i include lang in route params for Zf2. My valid routes are fine and it's working. But when i give a wrong route, this exception comes and it's not caught by zf2 :
Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException' with message 'No RouteMatch instance provided'[path]\vendor\zendframework\zendframework\library\Zend\View\Helper\Url.php on line 64
This is a sample of code wich i suspect to be invalid in case of wrong route :
<ul class="dropdown-menu">
<li><a href="<?= $this->url($this->route, array('lang' => 'fr'));?>">
<span class="flag fr"></span> Français
</a></li>
<li><a href="<?=$this->url($this->route, array('lang' => 'en'));?>">
<span class="flag gb"></span> English
</a></li>
</ul>
It makes sense, this->route is incorrect when a wrong path is provided, what i need to change for fix that please ?
If you take a look at line 62 of the Zend\View\Helper\Url
helper, it's clear that the exception will only be raised if you pass NULL
in as the $name
argument.
// ...Zend\View\Helper\Url.php
if ($name === null) {
if ($this->routeMatch === null) {
throw new Exception\RuntimeException('No RouteMatch instance provided');
}
Therefore you need to ensure that the $this->route
view variable is correctly set before you use it.
In your AnyModule\Module.php write lines below
public function onBootstrap(MvcEvent $e)
{
$application = $e->getApplication();
$eventManager = $application->getEventManager();
/**
* Zf2 View Url helper bug fix
* The problem is Url helper always requires RouteMatch
* if you used null in route name or set reuse matches to true
* even in 404 error but 404 itself means that there is not any route match ;)
*/
$eventManager->attach(
\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR,
function ($e) {
$application = $e->getApplication();
$serviceLocator = $application->getServiceManager();
$match = $application->getMvcEvent()->getRouteMatch();
if (null === $match) {
$params = [
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Index',
'action' => 'not-found',
// Here you can add common params for your application routes
];
$routeMatch = new \Zend\Mvc\Router\RouteMatch($params);
$routeMatch->setMatchedRouteName('home');
$application->getMvcEvent()->setRouteMatch(
$routeMatch
);
}
}
);
}