Richard Parnaby-King

Web Developer – PHP, Zend Framework and Actionscript 3

Posted on | | No Comments

First, some definitions:
A form action is the URI to which the form is submitted.
Zend_Form makes it easy for developers to create complex forms that filter and validate the date from a submitted form before returning it to the rest of the application for it to do whatever is needed. In this example we are assuming that you have extended Zend_Form to create your own form class, as opposed to creating a Zend_Form form in your controllers.
A route is how a Zend Framework application takes a URI endpoint (that part of the URI which comes after the base URL) and decomposes it into parameters to determine which module, controller, and action of that controller should receive the request.

And now the problem:
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.

It is possible to use a view helper ‘url’ to construct a route. If the route requires parameters you can pass those in as well to get the fully constructed route. For example, suppose you had the route:
[php]
addRoute(
‘complexRoute’, //the route name
new Zend_Controller_Router_Route(‘path/to/page/:id/:page’,
array(
‘module’ => ‘default’,
‘controller’ => ‘index’,
‘action’ => ‘some-action’,
//default values
‘id’ => 0,
‘page’ => 1
),
array(
‘id’ => ‘\d+’,
‘page’ => ‘\d+’
)
)
);
[/php]

Using $view->url():

[php]
url(array(), ‘complexRoute’);
//path/to/page

echo $view->url(array(‘id’ => 99), ‘complexRoute’);
//path/to/page/99

echo $view->url(array(‘id’ => 99, ‘page’ => 3), ‘complexRoute’);
//path/to/page/99/3
[/php]

Finally, what if you wanted to use a route in a Zend_Form object? You could set the action in the controller when you instantiate the form, however you may be instantiating the form in one controller, then submitting it somewhere else. How do you keep your form self-contained?

As of Zend Framework 1.8 you can access the view object inside your form. And from that, access the url view helper:
[php]
getView();
$url = $view->url(array(‘id’ => 99, ‘page’ => 3), ‘complexRoute’);
$this->setAction($url); //$this referring to your form
[/php]

If you are using an older version of Zend Framework then you will need to access the view object via the layout component:
[php]
getView();
$url = $view->url(array(‘id’ => 99, ‘page’ => 3), ‘complexRoute’);
$this->setAction($url);
[/php]

Posted By:

Comments

  • ABOUT

    Having eight years of programming experience in PHP, Zend Framework and ActionScript3, I have a very strong working knowledge of object orientated programming.

    I am a PC Gamer! Playing FPS, RTS, RPG and the occasional MMO since 1996 I have a huge number of a variety of fast-paced games.

  • Recent Posts

  • Categories

  • RSS SUBSCRIBE TO OUR FEED

  •