AI Reading
Quick summary of this article
This chapter explains how to create and manage forms in Zend Framework 3 using the ZendForm component. It shows how to build a form structure, add input fields, and enforce validation rules with ZendInputFilter to ensure user data is clean and secure before processing.
- Forms are built using the ZendFormForm class, where you add elements like text, email, hidden, and submit fields with labels and attributes.
- Validation and filtering rules are defined in a separate InputFilter class, which checks required fields, trims whitespace, strips HTML tags, and enforces length or email format constraints.
- In the controller, the form is linked to its input filter, and submitted data is validated using the isValid() method before being processed or saved.
- Forms are rendered in view scripts using helpers like form(), formRow(), and formSubmit(), which automatically generate the necessary HTML and display validation errors.
- Best practices include always using InputFilters for sanitization, keeping validation logic separate from controllers, and adding CSRF protection for sensitive forms.
Chapter 7: Forms and Validation in Zend Framework 3
✅ Introduction
Forms are essential in web applications for user input. Zend Framework 3 provides the Zend\Form component to easily create, render, and validate forms. Combined with Zend\InputFilter, you can enforce validation and filtering rules on submitted data.
✅ Key Concepts
- Zend\Form\Form: Class for building form structure.
- Form Elements: Fields like input, textarea, select, checkbox, etc.
- Zend\InputFilter: Validation and filtering logic for form data.
- Hydrators: Map form data to objects.
✅ Creating a Form
Create a simple UserForm class for adding/editing users:
namespace Application\Form;
use Zend\Form\Form;
class UserForm extends Form
{
public function __construct($name = null)
{
parent::__construct('user');
$this->add([
'name' => 'id',
'type' => 'hidden',
]);
$this->add([
'name' => 'name',
'type' => 'text',
'options' => [
'label' => 'Full Name',
],
]);
$this->add([
'name' => 'email',
'type' => 'email',
'options' => [
'label' => 'Email Address',
],
]);
$this->add([
'name' => 'submit',
'type' => 'submit',
'attributes' => [
'value' => 'Save',
'id' => 'submitbutton',
],
]);
}
}
✅ Creating InputFilter
Now define validation rules for the form:
namespace Application\Form;
use Zend\InputFilter\InputFilter;
class UserFilter extends InputFilter
{
public function __construct()
{
$this->add([
'name' => 'name',
'required' => true,
'filters' => [
['name' => 'StripTags'],
['name' => 'StringTrim'],
],
'validators' => [
[
'name' => 'StringLength',
'options' => [
'min' => 3,
'max' => 50,
],
],
],
]);
$this->add([
'name' => 'email',
'required' => true,
'validators' => [
[
'name' => 'EmailAddress',
],
],
]);
}
}
✅ Using Form in Controller
Inject the form into a controller and process input:
namespace Application\Controller;
use Application\Form\UserForm;
use Application\Form\UserFilter;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class UserController extends AbstractActionController
{
public function addAction()
{
$form = new UserForm();
$form->setInputFilter(new UserFilter());
$request = $this->getRequest();
if (! $request->isPost()) {
return ['form' => $form];
}
$form->setData($request->getPost());
if (! $form->isValid()) {
return ['form' => $form];
}
// Process valid data
$data = $form->getData();
// Save data into database...
return $this->redirect()->toRoute('user');
}
}
✅ Rendering Form in View
In your view script user/add.phtml:
<h2>Add New User</h2>
<?php
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('name'));
echo $this->formRow($form->get('email'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
?>
✅ Best Practices
- Always use InputFilters to validate and sanitize user input.
- Keep validation logic in filters, not in controllers.
- Use hydrators when mapping form data to entities.
- Apply CSRF protection for sensitive forms.
✅ Exercise
- Create a
PostFormwith title and content fields. - Add validation rules: title min 5 chars, content min 20 chars.
- Integrate it into a
PostControllerfor adding blog posts.
