AI Reading
Quick summary of this article
This chapter explains how to work with forms and validation in Zend Framework 3. It covers creating form classes, adding input filtering and validation rules, using forms in controllers, rendering them in views, and protecting forms with CSRF tokens. The main components are ZendForm for building HTML forms, ZendInputFilter for applying filters and validation, and ZendValidator for built-in validation logic.
- Install required components using Composer: zendframework/zend-form, zendframework/zend-inputfilter, and zendframework/zend-validator.
- Create a form class by extending ZendFormForm and adding elements like text fields, textareas, hidden fields, and submit buttons.
- Define validation rules in the form's getInputFilterSpecification() method, including required fields, string trimming filters, and string length validators (e.g., title must be 3-100 characters, content minimum 10 characters).
- In the controller, check if the request is POST, set form data from request, validate with isValid(), and only process or save data if validation passes.
- Always add CSRF protection using ElementCsrf to prevent cross-site request forgery attacks on forms that modify data.
Chapter 6: Forms & Validation in Zend Framework 3
✅ Introduction
Forms are essential for user interaction. In Zend Framework 3, the Zend\Form component helps build, validate, and filter form data. Combined with Zend\InputFilter and Zend\Validator, you can ensure data integrity and security.
- Zend\Form: Builds and renders HTML forms.
- Zend\InputFilter: Applies filters and validation rules.
- Zend\Validator: Provides built-in validation logic.
✅ Installing Required Components
composer require zendframework/zend-form
composer require zendframework/zend-inputfilter
composer require zendframework/zend-validator
✅ Creating a Form Class
// File: module/Blog/src/Form/PostForm.php
namespace Blog\Form;
use Zend\Form\Form;
use Zend\Form\Element;
class PostForm extends Form
{
public function __construct($name = null)
{
parent::__construct('post');
$this->add([
'name' => 'id',
'type' => Element\Hidden::class,
]);
$this->add([
'name' => 'title',
'type' => Element\Text::class,
'options' => [
'label' => 'Title',
],
]);
$this->add([
'name' => 'content',
'type' => Element\Textarea::class,
'options' => [
'label' => 'Content',
],
]);
$this->add([
'name' => 'submit',
'type' => Element\Submit::class,
'attributes' => [
'value' => 'Save',
'id' => 'submitbutton',
],
]);
}
}
✅ Input Filtering & Validation
We define validation rules using InputFilter.
// File: module/Blog/src/Form/PostForm.php
use Zend\InputFilter\InputFilter;
public function getInputFilterSpecification()
{
return [
'title' => [
'required' => true,
'filters' => [
['name' => 'StringTrim'],
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'min' => 3,
'max' => 100,
],
],
],
],
'content' => [
'required' => true,
'validators' => [
[
'name' => 'StringLength',
'options' => [
'min' => 10,
],
],
],
],
];
}
✅ Using the Form in a Controller
// File: module/Blog/src/Controller/PostController.php
public function addAction()
{
$form = new \Blog\Form\PostForm();
$request = $this->getRequest();
if (! $request->isPost()) {
return ['form' => $form];
}
$form->setData($request->getPost());
if (! $form->isValid()) {
return ['form' => $form];
}
$data = $form->getData();
// Save to database using PostTable
$post = new \Blog\Model\Post();
$post->exchangeArray($data);
$this->postTable->savePost($post);
return $this->redirect()->toRoute('post');
}
✅ Rendering the Form in Views
// File: module/Blog/view/blog/post/add.phtml
<h2>Add New Post</h2>
<?php
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('title'));
echo $this->formRow($form->get('content'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
?>
✅ Adding CSRF Protection
// Inside PostForm constructor
$this->add([
'name' => 'csrf',
'type' => Element\Csrf::class,
]);
✅ Best Practices
- Always use
InputFilterto sanitize and validate input. - Enable CSRF tokens for forms that modify data.
- Use built-in validators like
EmailAddress,Digits,Regex. - Keep validation rules inside the form or separate input filter classes.
✅ Exercises
- Create a
RegisterFormwith fields for name, email, and password. - Add validators: email format, password minimum length.
- Render the form in a controller and test validation errors.
- Add CSRF token to prevent form resubmission attacks.
