The Symfony Form Component for API Contracts

Murilo Lobato
SocialBase
Published in
3 min readApr 27, 2018

I’ve been working with Symfony for a reasonable time. It’s something about five years now, and a lot of things had changed in the last years. I’ve already started with Symfony in its second phase, when Symfony 2.0 was in its early stages.

Symfony 2.0 introduced a lot of great components, like Security and Form, among others. Since the beginning, the Form component catch my attention, mostly because its powerful feature of generating a HTML representation in conjunction with TWIG, and later because its even more powerful validation capabilities in conjunction with the Validation component.

In a common scenario, any web application must transform a request into a response. The Form component comes in place, in the controller, when we need to extract data from the request body and instantiate an object (or create an array) and validate its contents.

A controller using the Form component

The Form component provides two big pillars for validation, the first one is the schema, when the developer is defining the properties in the form he is also creating a contract for what must be present in the request body, and what type each property must obey. The second one, is that for each property that the developer specify in the form he can also add constraints. This way, we can guarantee the schema, property types and also properties with valid values.

A Form type

All this time working with Symfony and the Form component showed me that this is a extremely well designed component, it fits every use case I ever had. Since the most basic to the most complex validation scenario.

The Form component can combine validation constraints on each property and also on the entity. An constraint in the entity can be used to create conditional validations. It can also execute different validation groups, because the same entity can have multiple validation scenarios.

It’s also possible to create batches of properties to validate. This can be useful when you want to create wizards, or create logical validation groups of failures.

Form types also provide a consistent way to create data transformers and data filters. These can be useful to change how a user interacts with the application to inform some data and how the application will store this data on the database.

At SocialBase, we use the Form component to guarantee our REST API’s contracts, and also for property values validation. With it, we were able to define a coding pattern among developers in how to evaluate and validate information sent to ours PHP applications.

In resume, we are talking about a powerful component that can be a little tricky to learn, but it will bring a valuable quality and consistency to your application.

See more detailed information at: http://symfony.com/doc/current/forms.html

--

--