Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 15 ■ INTRODUCTION TO THE ZEND FRAMEWORK^231

Listing 15-17. Modifying the Add View (in add.phtml)

<?php if(isset($this->messages)) { ?>
<?php foreach($this->messages as $message) { ?>
<?php echo $message; ?><br />
<?php } ?>
<?php } ?>

When you submit a blank value, it should fail to validate. If you enter an HTML tag, it
should be filtered.
The arrays for validators and filters are where the real magic happens. The values demon-
strated in the previous listings are extremely basic, but you can use significantly more complex
validations. For validators, you may provide an array to apply multiple validators to a single
field. For example, if you wanted to require that name contained only characters you could add
the Alpha filter, as shown in Listing 15-18.

Listing 15-18. Using Multiple Validators

$validation = array(
'name' => array (
array('StringLength', 1, 64),
'Alpha'
)
);

You will notice that only the validator’s name was used, not an array. This is because not
all validators require parameters. The first format passes the values after the validator name to
the validation class as constructor parameters. The second format doesn’t have any parameters at
all.
To find a list of built-in validation classes, locate the following path in your Zend Frame-
work library installation:

/ZendFramework-1.0.3/library/Zend/Validate

Here, you will find a set of files that contain validation classes that you may use immedi-
ately. The parameters they take are defined by each class’s __construct() method.
Similar to validators, filters can be chained. The following is the path to find information
about filters:

ZendFramework-1.0.3/library/Zend/Filter

Take a look at the StripTags filter. You will notice that it takes a number of parameters, not
the least of which is a list of allowed tags. I encourage you to experiment with different combi-
nations of filters and validators to find a mix that works for your forms.
You may also notice that the error messages presented when a field fails to validate are
rather terse, and you might want to change the default messages.

McArthur_819-9C15.fm Page 231 Thursday, February 28, 2008 7:44 AM

Free download pdf