PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Putting it together

Let's build a simple login form. It will need elements representing:

  • username

  • password

  • submit

For our purposes, let's assume that a valid username should be alphanumeric characters only, start with a letter, have a minimum length of 6, and maximum length of 20; they will be normalized to lowercase. Passwords must be a minimum of 6 characters. We'll simply toss the submit value when done, so it can remain unvalidated.

We'll use the power of Zend_Form's configuration options to build the form:

<?php
$form 
= new Zend_Form();
$form->setAction('/user/login')
     ->
setMethod('post');

// Create and configure username element:
$username $form->createElement('text''username');
$username->addValidator('alnum')
         ->
addValidator('regex'false, array('/^[a-z]+/'))
         ->
addValidator('stringLength'false, array(620))
         ->
setRequired(true)
         ->
addFilter('StringToLower');

// Create and configure password element:
$password $form->createElement('password''password');
$password->addValidator('StringLength'false, array(6))
         ->
setRequired(true);

// Add elements to form:
$form->addElement($username)
     ->
addElement($password)
     
// use addElement() as a factory to create 'Login' button:
     
->addElement('submit''login', array('label' => 'Login'));

Next, we'll create a controller for handling this:

<?php
class UserController extends Zend_Controller_Action
{
    public function 
getForm()
    {
        
// create form as above
        
return $form;
    }

    public function 
indexAction()
    {
        
// render user/form.phtml
        
$this->view->form $this->getForm();
        
$this->render('form');
    }

    public function 
loginAction()
    {
        if (!
$this->getRequest()->isPost()) {
            return 
$this->_forward('index');
        }
        
$form $this->getForm();
        if (!
$form->isValid($_POST)) {
            
// Failed validation; redisplay form
            
$this->view->form $form;
            return 
$this->render('form');
        }

        
$values $form->getValues();
        
// now try and authenticate....
    
}
}

And a view script for displaying the form:


<h2>Please login:</h2>
<?php echo $this->form ?>

As you'll note from the controller code, there's more work to do: while the submission may be valid, you may still need to do some authentication using Zend_Auth or another authorization mechanism.

Zend Framework