Equivalent of url() helper function in Zend controller
Asked Answered
S

4

14

In the Zend view helper, there is the function url() for outputting a URL based on the routing tables eg

$this->url(array('controller' => 'comments', 'action' => 'add')

How can I do the same thing in a controller? In particular I want to set the action URL for a Zend Form using controller/action syntax rather than a standard URL eg

$form = new Zend_Form;
$form->setMethod('post')->setAction( $this->url(array('controller' => 'comments', 'action' => 'add')) );
Saker answered 5/11, 2009 at 14:13 Comment(0)
P
23

There is an action helper for this: Zend_Controller_Action_Helper_Url. Inside an action controller, you can access it using:

$this->_helper->url($action [, $controller [, $module [, $params]]]);

or:

$this->_helper->url->url(array(...));

Alternatively, you can also use the view helper:

$this->view->url(...);
Placoid answered 5/11, 2009 at 14:20 Comment(2)
If I call $this->_helper->url(array('controller' => 'index', 'action' => 'download')) outside the IndexController (here AjaxController) it returns '/ajax/Array' what did I do wrong? Or is it a bug?Incompletion
Use $this->_helper->url('download', 'index') or $this->_helper->url->url(array('controller' => 'index', 'action' => 'download')). I will update my answer and add a link to the API docs.Placoid
D
3

I've actually found out that only this works:

// in your form
public function init()
{
    $router = Zend_Controller_Front::getInstance()->getRouter();
    $url = $router->assemble(
        array(
            'paramterName0' => 'parameterValue0',
            'paramterName1' => 'parameterValue1',
        ),
        'routeName'
    );

    $this->setAction($url);
    ...
}
Drawknife answered 10/4, 2011 at 11:1 Comment(0)
S
2

Was able to answer my own question as it seems the following code does the trick:-

$form = new Zend_Form;
$form->setMethod('post')->setAction( $this->getHelper('url')->url(array('controller' => 'index', 'action' => 'add')) );
Saker answered 5/11, 2009 at 14:18 Comment(1)
I now use $this->view->url(array('controller' => 'index', 'action' => 'download')), not nice but works inside the controller.Incompletion
A
1

In zf3 you can use:

    $form = new YourFormClass();
    $form->setMethod('post')->setAction($this->url()->fromRoute(array('controller' => 'index', 'action' => 'add'));
Allie answered 5/5, 2017 at 4:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.