Symfony: Denote Required Form Fields
You can checkout the full gist for this tutorial here.
The symfony form framework separates a form’s presentation and validation into
two distinct collections of classes: widgets and validators. For the most
part, these two codebases live happily without any knowledge of eachother.
When data from the validators needs to be shown in the presentation layer,
such as in the case of error messages, symfony provides the sfFormField
class, which bridges this divide.
One common requirement for web forms is that required fields must be apparent to the user. Implementing this in the symfony form framework may not seem possible, because of the divide between widgets and validators, but it is in fact quite possible, and easily implemented.
This is a quick tutorial on how to do just that.
Validator, meet Widget
The first step is for the form’s validators to inform the form’s widgets which of its fields are required. We can do this by passing a array of field names to the widget schema once the form is fully configured:
The getRequiredFields() method returns a simple array of formatted field
names that corresponds to those validators marked as required. It accomplishes
this by recurrisively iterating through the form’s validators:
Label Formats
Once the form’s widgets know which fields are required, it’s up to the form formatter to decorate those fields accordingly. I’ve done this using an extension of the standard table formatter class:
Finally, we just add this custom formatter to our forms by adding the
following to the overloaded __construct() method from above:
Your forms’ required fields should now render with labels that include the
required class. Of course, you can do something different in the formatter
to suit your needs, add a * or add a class to the entire row, but hopefully
the implementation should now be clear.