A free and open-source book on ZF3 for beginners


7.6. Forms and Model-View-Controller

In the previous section, we've considered a very simple form usage case: we prepared the view template with form HTML markup and a controller action responsible for displaying the form and dumping raw user input to the screen. However, using raw user input in real-life applications has a disadvantage in that we do not check user-submitted data for possible errors and/or malicious code. Here we will discuss how to perform such validation.

In a ZF3-based web site that uses the Model-View-Controller pattern, form functionality is usually separated into form models responsible for field definition, filtering and validation; and form presentation (view) which is typically implemented with the help of special view helpers.

The functionality allowing to create form models, add filtering and validation rules and use view helpers, is schematically shown in figure 7.8. As you can see from the figure, the standard HTML forms functionality is used as a base.

Figure 7.8. Form Functionality in ZF3 Figure 7.8. Form Functionality in ZF3

The MVC approach to working with forms has the following advantages:

7.6.1. A Typical Form Usage Workflow

Generally speaking, you instantiate a form model inside of your controller's action method, then you retrieve the user-submitted data from PHP variables, and pass it to the form model for validation. Form view helpers are used in a view template for generating HTML markup of the form. This typical workflow is illustrated by figure 7.9.

Figure 7.9. Working with form in an MVC application Figure 7.9. Working with form in an MVC application

Arrows in figure 7.9 denote the direction of the actions:

  1. First, inside of the controller's action method, you retrieve the data submitted by the site user from GET, POST (and possibly other) PHP variables. Then you create an instance of the form model and pass it the user-submitted data. The form model's work is to check (validate) the data for correctness, and if something is wrong, produce error message(s) for any invalid form field.

  2. Secondly, you pass the form model to the .phtml view template for rendering (with the help of the ViewModel variable container). The view template then will be able to access the form model and call its methods.

  3. And finally, the view template uses the form model and the view helpers provided by Zend Framework 3 to render the form fields (and to display possible validation error messages produced at the validation stage). As a result, the HTML markup of the form is produced.

In the following sections, we will discuss these in more detail.


Top