0
votes

I have this piece of code written in Application/view/layout/layout.phtml for adding a link which will be pointing to current page. This I added for debugging purpose for refreshing the current page.

<li class="active"><a href="<?php echo $this->url() ?>"><?php echo $this->translate('Refresh') ?></a></li>

This is working fine as long as I don't invalid route (404 error). I get below fatal error

Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException' with message 'No RouteMatch instance provided'

I wan't to handle this by adding a condition to check if its a 404 error or an invalid route before trying to render the url. I am not sure how to do it. I tried to look the source code of Zend\View\View class and ViewModel class to see if there is a way I can get error code or something which can tell its a 404 error.

Edit:

As a last resort I have adding the try catch block like below which is working fine but want to check if there is any elegant way

<?php
   try{
       $url = $this->url();
?>       
  <li class="active"><a href="<?php echo $url ?>"><?php echo $this->translate('Refresh  ') ?></a></li>
  <?php
     } catch (Exception $ex) { 
   }
?>
1

1 Answers

1
votes

The exception message you are getting is not because the route is undefined but rather that the routeMatch parameter of the URL view helper, Zend\View\Helper\Url, has not been set.

Normally when using the URL helper you can provide the name of the route as the first argument. The helper will internally use the router and route match to generate the correct URL string based off the route configuration.

For example

echo $this->url('test'); // will create the route matching the test route name

The helper also allows you to provide no route name, $this->url(), in which case it will use the last matched route by default when creating theses routes. There is however one special case when you cannot rely on this; when the application cannot match a route, there will be no RouteMatch available.

So using this shorthand convenience method in the layout.phtml when the application tries to load the 404 error template (which is wrapped by the layout.phtml) the URL view helper will have no RouteMatch available and throw the error you received.

To fix this you should always provide a route name when calling the URL view helper in the layout or error scripts.