March 4th, 2009The Action View Helper
Situation:
I use Zend_Layout to create a global view template for my website and the view (.phtml) that corresponds to a controller/action will be loaded into the $this->layout->content variable automatically.
All good but what to do with a form in your global template?
Building the form (Zend_Form) into your view isn’t really a clean option and what about validation of the form? There is no controller/action from where the form was build and so there is no controller/action where to post the form to.
Solution:
I read through the Zend manual and I discovered there was a view helper named ‘Action’.
What does it do?
It enables you to call a controller/action from within your view script. It will process the controller/action code, render the view and return it into your view script.
Example:
IndexController.php
classIndexControllerextendsZend_Controller_Action {
public function indexAction(){
}
public function formAction(){
//build a form
$form = new Zend_Form();
//create a text element
$elementName = new Zend_Form_Element_Text(’name’);
$element->setRequired(true); //a validation saying our field has to be filled out
//create a submit button
$elementSubmit = new Zend_Form_Element_Submit(’submit’);
$elementSubmit->setLabel(’Send’);
//add elements to the form
$form->addElement($elementName);
$form->addElement($elementSubmit);
//if we click the ‘Send’ button
if($this->getRequest()->isPost()){
if($form->isValid()){
//form is valid
}
}
//add the form to a view variable
$this->view->form = $form;
}
}
index/form.phtml
<?php echo this->form; ?>
layout.phtml
<?php echo$this->doctype(Zend_View_Helper_Doctype::XHTML1_STRICT) . “\n”; ?>
<html>
<head>
</head>
<body>
<div id=”container”>
<?phpecho$this->layout()->content.”\n”;?>
</div>
<div>
<?php echo $this->action(’form’, ‘index’); ?>
</div>
</body>
</html>
parameter list of the view action
action($action, $controller, $module = null, array $params = array())
Result:
The form action of the index controller is called from the layout.phtml.
The business logic is executed, the view (index/form.phtml) is rendered and is returned to our layout.phtml.
When we press the ‘Send’ button in our form. The form will be submitted to index/form and the validation will happen.
No Tags



