Scott Scott - 4 months ago 25
PHP Question

ZF2 - Get current URL in Controller

This seems like it should be a simple task. I need the current URL from a function within the Controller. This function can be called from multiple actions, and the end goal is to set a form's action attribute. (Side note: It appears IE does not send an ajax request if the URL starts with '#').

I feel like my google-fu is off today because I could not find a good way to do this Zend Framework 2. I have this line currently, but it feels very bulky:

$this->url()->fromRoute(
$this->getServiceLocator()
->get('Application')
->getMvcEvent()
->getRouteMatch()
->getMatchedRouteName()
);

Answer

Couldn't you just get the URI from the request object:

$this->getRequest()->getUriString()

Provided your controller extends Zend\Mvc\Controller\AbstractActionController.

Note: This would output the entire URL, like so:

 http://example.com/en/path/subpath/finalpath?test=example