- 2008-04-05 (Sat) 7:00
- Zend_Form
intro
Let's validate submitted data using Zend Form.You can download the source code of this article from here.
1.Create Controller
Create the file
application/constorllers/IndexController.php with the following content.
<?php require_once 'Zend/Controller/Action.php'; require_once 'Zend/Form.php'; class IndexController extends Zend_Controller_Action { public function getProfileForm() { $form = new Zend_Form(); $form->setAction($this->_request->getBaseUrl() . '/index/profile') ->setMethod('post'); $givenName = $form->createElement('text', 'givenName'); $givenName->setLabel('Given Name') ->setRequired(true) ->addFilter('stringTrim') ->addValidator('stringLength', false, array(1,50)); $familyName = $form->createElement('text', 'familyName'); $familyName->setLabel('Family Name') ->setRequired(true) ->addFilter('stringTrim') ->addValidator('stringLength', false, array(1,50)); $email = $form->createElement('text', 'email'); $email->setLabel('E-Mail') ->setRequired(true) ->addFilter('stringTrim') ->addValidator('emailAddress', false); $url = $form->createElement('text', 'url'); $url->setLabel('URL') ->setRequired(false) ->addFilter('stringTrim') ->addValidator('stringLength', false, array(1,100)); $submit = $form->createElement('submit', 'submit'); $submit->setLabel('Send'); $form->addElements(array( $givenName, $familyName, $email, $url, $submit )); return $form; } public function indexAction() { $this->_forward('profile'); } public function profileAction() { $form = $this->getProfileForm(); if ($this->getRequest()->isPost()) { if ($form->isValid($_POST)) { $values = $form->getValues(); $this->view->values = $values; } } $this->view->form = $form; } }
2.Create View
Create the file
application/views/scripts/error/profile.phtml with the following content.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Zend Framework Quick Start</title> </head> <body> <h1 id="5_basic-blog_1" ><?= $this->translate('Your Profile'); ?></h1> <?php if($this->values) : ?> <h3 id="5_submitted" > <?= $this->translate('You just submitted the following values'); ?>: </h3> <ul> <?php foreach ($this->values as $value) :?> <li> <?= $this->escape($value); ?> </li> <?php endforeach; ?> </ul> <?php else : ?> <?= $this->form; ?> <?php endif; ?> </body> </html>
3.Check
Let's access your web server and check how this simple validation program works.
- Newer: Standard Validators of Zend Framework
- Older: Use of Zend_Form(i18n)
Comments:0
Trackbacks:0
- Trackback URL for this entry
- http://www.oplabo.com/article/10/trackback
- Listed below are links to weblogs that reference
- Validation of Zend_Form from Open Programming Laboratory