symfony 1.1 form framework and the MVC pattern

January 15, 2008

Even if the symfony 1.1 form framework is not yet documented, a lot of people are already using it. That's great news as I think this is one of the major new features of symfony 1.1 and probably the one I'm the most proud of.

I've spent more than a year and a half designing and coding the form framework and most of this time was spent ensuring it sticks to the MVC pattern. So, I was a bit disappointed when I read his questions. I will try to explain the MVC philosophy behind the new form framework in this post.

Before I start, you may have noticed that I call the new form system a "framework". That's right, it is a framework by itself. You can use it without symfony. There is no dependency between the new form framework and the rest of symfony. As a matter of fact, hartym has packaged the form framework in a plugin for symfony 1.0. This also means that you can use it with the Zend Framework or even with plain PHP. The only requirements is to use PHP 5.1.3 or later.

Those two libraries have done a wonderful work but I think the symfony form framework does one thing better: it is really MVC compliant. I have put the extra effort to ensure that every single line of code belongs to the right layer and that all layers are really decoupled and useable by themselves.

The validator classes handle the logic needed to validate the raw data and clean/convert the data to validated and consistent data (convert dates to timestamp, convert the unusable PHP $_FILES array to sfValidatedFile objects, etc...). Moreover, the validator sub-framework is totally decoupled from the rest of symfony. So, you can use it by itself. You can use it to validate any input source, be it an XML file, objects...

The widgets classes render the form (in HTML by default) to display it to the user. Like the validator sub-framework, the widget sub-framework is totally decoupled from the rest of symfony... which means you can use it by itself. In fact, we will use it for non form widgets in the future.

The form is rendered in the template. The simplest way to render the form is:

But, keep in mind that the echo $form is just a nice shortcut. It's a great way to prototype a working form but most of the time, you want greater control on the form layout and how to arrange the different widgets together. And this is where the new system really shines. The designers work is greatly simplified. Let's compare how to display an input tag in symfony 1.0 and symfony 1.1:

// render errors for a field as a list
renderError() ?>
// render the label tag for a field (with the proper for attribute)
renderLabel() ?>
// render the whole row for a field (label, tag, help and errors)
renderRow() ?>