Zend Form SetAction Using Named Routes

与世无争的帅哥 提交于 2019-11-30 08:56:59

Method 1: Get the router

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

    $this->setAction($url);
    ...
}

Method 2: Get an instance of the View object and call the url-view-helper directly

// in your form    
public function init()
{
    $url = Zend_Layout::getMvcInstance()->getView()->url(array(), 'routeName';
    $this->setAction($url);
    ...
}

I prefer Method 1. It is more verbose but you have one dependency less in your form.

if in my controller action:

$this->view->form = $form;

I will use view helper url to generate the form action url in my view script ( xxx.phtml):

$url = $this->url(array('controller'=>'my-controller-name', 
                    'action'=>'my-action-name'), 
              'my-route-name'
             );

$this->form->setAction($url);

echo $this->form;
Stephan de Souza

Nowadays you can access the Zend_View object via getView() method on Zend_Form classes:

// init your form    
public function init()
{
    $view = $this->getView();
    $url = $view->url(array('module'=>'login','action'=>'login'));
    $this->setAction($url);
    ...
}

Might this help on ZF 1.8+

I do not know when it was added, but there is an even simpler solution.

You can retrieve the form's view object with getView(), which has access to the registered routes.

//In the form
$this->setAction($this->getView()->url(array('param1' => 'value1'), 'routeName'));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!