Guides Forms Processing with the Zend Framework

Forms Processing with the Zend Framework

Introduction


One of the key reasons for the meteoric rise of the World
Wide Web is that unlike television, radio, or the
traditional newspaper, it offers an immediate conduit for
two-way communication. Yet many Web developers, particularly
those with relatively little experience, seem to place
remarkably little emphasis on devising efficient methods for
accepting and processing user-provided information. Much of
the reason for such oversight is due to complexity;
effectively validating a complex string such as an e-mail
address, or ensuring that a password is of a certain length
are programmatic tasks which can strain the boundaries of
many beginning developers’ knowledge. Additionally,
developers need to understand how to effectively respond to
errors which crop up in the validation process, whether it’s
providing the user with error-specific feedback, or
repopulating the form in order to not discourage the errant
user from correcting his errors and submitting the form
anew.


Given the universal challenge forms processing presents
to Web developers no matter the project, it’s no wonder that
implementing an efficient forms processing solution is often
high on the priority list of most Web framework developers.
The Zend Framework is no different, offering developers a
powerful solution for not only validating forms data, but
actually programmatically building the form HTML. In this
tutorial I’ll introduce you to the Zend Framework’s
validation feature, showing you how easy it is to not only
validate user provided data with confidence, but also how to
inform the user of the error should validation fail.


Introducing the Zend_Validate Component


These days most serious Web sites provide the visitor
with an opportunity to become a registered user in order to
access restricted material or customized content. Because
the number of registered users is often directly
proportional to a Web site owner’s income, it’s crucial for
the registration step to be streamlined and convenient in
order to give the visitor every incentive to complete the
process. Although you should keep the required registration
fields to a minimum in order to provide the user with the
shortest path to completion, the validation necessary to vet
the data often goes beyond merely determining whether a
field was left blank. Figure 1 presents what such a
registration form might look like.

A Web site registration form

Figure 1. A Web site registration form

Although consisting of just five fields, validating this
form presents several challenges:




  • Name: The name field must not be blank.

  • E-mail Address: The e-mail address field must not be
    blank, and must contain a valid e-mail address as defined by
    RFC 2822.

  • Password: The password must not be blank, and must
    consist of at least six characters. Further, the password
    and confirmed password must match.

  • Terms of Service: The check box must be checked.



Using the Zend Framework’s Zend_Validate
component, carrying out these field validations is a trivial
process. Zend_Validate offers developers an
extensive suite of validation procedures capable of ensuring
data meets a wide variety of specifications, such as whether
a number falls within a certain range, a credit card is
valid as defined by the Luhn algorithm, or a value falls
within a predefined list of valid values as defined by
elements within an array. These procedures are packaged
within the component as a number of different classes, with
each class serving a specific validation purpose. See this
page of the Zend Framework manual for a complete list of
what’s available.


To validate the fields, first you’ll invoke the
Zend_Validate() class, and then add validators
by passing each to the addValidator() class,
like this:




$validator = new Zend_Validate_NotEmpty();


Next you’ll call the isValid() method,
passing in the field you’d like to validate. If the
isValid() method returns FALSE, you can call
the getMessages() method to retrieve a list of
predefined error messages.




if (! $validator->isValid($this->_request->getPost(‘name’))) {
echo “The name is not blank”;
} else {
foreach($validator->getMessages() as $message) {
echo “{$message}<br />”;
}
}


As I mentioned, the Zend_Validate component’s
capabilities go well beyond merely checking a value for
existence. For instance, to validate an e-mail address, you
can both ensure the value is not blank and that it meets the
requirements as defined by RFC 2822 by invoking the
EmailAddress class:




$validator = new Zend_Validate_EmailAddress();

if (! $validator->isValid($this->_request->getPost(’email’)) {
echo “Please provide your e-mail address.”;
}



Streamlining the Validator Invocation Process


Although it’s possible to invoke each validation class as
needed, you can use a very convenient static method named
Zend_Validate::is() to streamline the
invocation process. For instance, to determine whether a
field is blank, you can invoke the NotEmpty
class like this:




if (! Zend_Validate::is($data[’name’], ‘NotEmpty’)) {
echo “Please provide your name.”;
}

Customizing Error Messages


When an error occurs, the getMessages()
method will retrieve a list of predefined error messages.
However, these messages can be quite terse; For instance, in
the case the Zend_Validate_NotEmpty() validator
determines a value to be empty, the following error message
will be provided:




Value is required and can’t be empty


This isn’t exactly an ideal message, if for any other
reason because it doesn’t tell the user precisely which
value is required and can’t be empty. You can override the
default messages




$validator->setMessages(array(Zend_Validate_NotEmpty::IS_EMPTY => “Please provide your name.”));


Next, rather than output the error messages using a
for loop within your controller action (which
would break the MVC paradigm), create an array used to
contain errors, and then assign the
getMessages() return value to it:




$this->view->errors = array();
$this->view->errors = $validator->getMessages();


Finally, to present the errors in a well-organized
fashion, I like to use a custom view helper which can be
repeatedly used throughout the Web site as desired:




<?php

class Zend_View_Helper_Errors extends Zend_View_Helper_Abstract
{

public function Errors($errors)
{

echo “<div id=’errors’>”;
echo “<p>Errors were found:</p>”;
echo “<ul>”;

foreach ($errors AS $error) {
echo “<li>$error</li>”;
}

echo “</ul>”;
echo “</div>”;

}

}

?>



Within the view, you can call the helper like this:




<?php if (count($this->errors) > 0) { ?>
<?= $this->Errors($this->errors); ?>
<?php } ?>


After some CSS styling, attempting to submit the form
with a blank name will produce the error message shown in
Figure 2.

Displaying an error message

Figure 2. Displaying an error message

Validating Multiple Fields


Of course, chances are your form will contain multiple
fields, such as the aforementioned registration form.
Because you’ll need to validate each field, it’s possible
that several errors could crop up. You’ll need to keep track
of all errors and present them to the user. To do this, I
like to eliminate the need to use the
getMessages method altogether and just use my
own simple error tracking feature, like this:



$this->errors = array();

if (! Zend_Validate::is($this->_request->getPost(‘name’), ‘NotEmpty’)) {
$this->errors[] = “Please provide your name.”;
}

if (! Zend_Validate::is($this->_request->getPost(’email’), ‘EmailAddress’)) {
$this->errors[] = “Please provide a valid e-mail address.”;
}

if (count($this->view->errors) > 0) {
$this->view->errors = $this->errors;
} else {
// Continue with processing
}



Where to From Here?


Processing user input is such a commonplace task within
Web sites of all sizes and purposes, that there’s really no
excuse to not rely upon a well-organized approach such as
the one offered by the Zend Framework. In fact, forms
processing is so important that the framework actually
offers quite a bit more functionality than what has been
introduced in this tutorial. Check out the following links
for more information!




  • The Zend_Form Component: This component gives developers
    the ability to not only programmatically create forms, but
    also filter and validate input.

  • The Zend_Filter_Input Component: This component
    offers developers a means for declaratively identifying
    which form fields must be validated.



About the Author


Jason Gilmore is founder of EasyPHPWebsites.com, and author of the popular book, “Easy PHP Websites
with the Zend Framework
“. Formerly Apress‘ open source
editor, Jason fostered the development of more than 60
books, along the way helping to transform their open source
line into one of the industry’s most respected publishing
programs. Over the years he’s authored several other books,
including the best-selling Beginning PHP
and MySQL: From Novice to Professional
(currently in its
third edition), Beginning PHP
and PostgreSQL: From Novice to Professional
, and Beginning PHP
and Oracle: From Novice to Professional
.


Jason is a cofounder and speaker chair of CodeMash, a nonprofit
organization tasked with hosting an annual namesake
developer’s conference, and was a member of the 2008 MySQL
Conference speaker selection board.


Jason has published more than 100 tutorials and articles
within prominent publications such as Developer.com, Linux Magazine, and TechTarget.

Latest Posts

Related Stories