Zend Framework Tutorial
By Lyndon Baptiste2008-08-13
Validating Our Form
When the page is refreshed you should see the results denoted in Figure 5. You will recall on line 17 of the class IndexForm we specified the class attribute. Line 15 of this same class dictates that a post will be to the save action of the default controller. This is where validation and database access becomes important so we'll tackle the two areas sequentially. Create a save action in the index controller of the default module. This time before I show the code let's discuss the sequence of events.
1. We have to get back the Zend_Form object through a call to the same method that created the form.
2. We have to test the form to see if it is valid against the superglobal $_POST.
3. If the form is not valid we have to store the form in the view object and render the register script.
4. If the form is valid we have to proceed to save the values in the database.
We'll extend saveAction as we go along. Let's cater for steps 1 to 3 first of all:
public function saveAction() {
require_once './application/modules/default/models/IndexForm.php';
$form = IndexForm::registerForm();
//handle if form is invalid
if (!$form->isValid($_POST)) {
$this->view->form = $form;
$this->render('register');
return;
}
}
Firstly we require and get the form object. Zend_Form has a method isValid that takes an associative array. If the form is invalid when checked against the validators we specified in IndexForm the method returns false. In this case we can simply register form with the view object and render the register.phtml script. We must return the method thereafter.
Catering for step 4 means we require a model file that can do the work easily for us. Let's take a look at Zend_Db_Table.
Tutorial Pages:
» Introduction
» The index.php File
» Actioning Requests
» The IndexController
» The View and Layout
» Zend_Form
» CSS Code
» Validating Our Form
» Zend_DB_Table
» Back To The Controller
» Back to Zend_DB_Table
» Putting Zend_Registry and Zend_Cache Into Perspective
» Conclusion
