Zend Framework

Zend Framework 3 Tutorial – Chapter 7: Forms and Validation

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 PostForm with title and content fields.
  • Add validation rules: title min 5 chars, content min 20 chars.
  • Integrate it into a PostController for adding blog posts.

Leave a Reply

Your email address will not be published. Required fields are marked *