Zend Form SetAction Using Named Routes

zend-formzend-frameworkzend-route

I have a form that I am trying to set the action for. I want to declare the action inside my form file (which extends Zend_Form) instead of in a controller or view, using a route I have created in my bootstrap.
Usually when I want to use a route I do something like

$this->url(array(), 'route-name');

in the view, or

$this->_helper->url(array(), 'route-name');

in the controller.

How do I call a route from within Zend_Form?


edit:
I have given up trying to load a route into zend_form. Perhaps in a future release there may be a function to easily do this?

I have created a viewScript for my form and set the route in that:
In the form init function:

$this->setDecorators(array(
    'PrepareElements',
        array(
            'ViewScript', array(
                    'viewScript' => 'forms/formView.phtml'
            ))));

and in the view file:

<form method="post" action="<?php echo $this->url(array(), 'route-name'); ?>" enctype="application/x-www-form-urlencoded">
    <?php
        foreach ($this->element->getElements() as $element)
        {
            echo $element;
        }
    ?>
</form>

Best Answer

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.

Related Topic