Use form with Pomm in Silex

Posted 6 years ago.

One may be tempted to use Postgresql's nice constraint system to validate forms but it is indeed a bad idea. Forms are business oriented rules, there can be multiple forms with multiple validation rules for the same group of database objects. Moreover, these rules can change often. Coding them in the PHP layer is by far a best choice and Symfony provides two components: form and validator. These components are integrated in the Symfony Standard Edition Framework but they can also be used with your own development framework and ... the Silex µ-framework.

This post will show a small example on how to create and validate form using Silex.

Form class creation

If you read the documentation of the Form component you could be puzzle about how to set up your forms amongst the many ways made possible by this nice piece of software. The Silex documentation also proposes a simple and efficient way to achieve validation with forms. The first difference with the documentation is that we are using Pomm hence non POPO entities. Since entities values are not stored in real attributes nor use real getters, it is not possible to use the java-ish implementation of the validator metadata classes.

Fortunately, the Form component is very modular and accepts to declare validation rules directly with from the FormBuilder. Let's create a Form class in a dedicated namespace of our application:

What do we have here ?

A class that extends the AbstractType and implements the two abstract methods needed to create a form:

  • buildForm is trigged by the form factory to describe the form.
  • getName is used to store the form's values.

The great thing here is the form builder accepts validation rules as parameter of each field allowing developers to set in one shot fields definition and validation.

Set up the form

This controller's goal is to display a blog post and a form for comments. The first lines retrieve the blog post with all its comments (if any) using a specific query of the model layer. If the post does not exist, the URL points to a non existent resource and 404 error page is returned.

Then, the form factory is invoked with our Form\Comment instance as argument and the view is extracted from the form and passed to the template.

Validate the form

The code is almost self explanatory. It looks quite the same as the previous example but instead of extracting the view from the form, the validate method triggers the validation set up in the Form\Comment. It is then easy to check if the form is valid or not. If it is the case, the createAndSaveObject method is called to hydrate and save a comment object from the cleaned values.