Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
  );
like image 888
Scott Avatar asked Dec 25 '22 09:12

Scott


2 Answers

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
like image 173
Jeffwa Avatar answered Dec 31 '22 01:12

Jeffwa


If your request route is like this:

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

And You want only this:

/en/path/subpath/finalpath?test=example

You can simply do : $this->getRequest()->getRequestUri()

To specify my Request object is an instance of

\ZF\ContentNegotiation\Request

like image 32
Carlos Zerga Avatar answered Dec 31 '22 01:12

Carlos Zerga