My friends and family are under attack in Ukraine. Donate to protect them directly or help international organizations.

Symfony Form: Extract Values

September 8th, 2011

I had to look deep into Symfony 1.4 code this morning as I was trying to get a field's value. Form values come from different sources: default values, record values (when editing, for example), original POST values and clean POST values. So when is each available and how do we get it?

Get the values by type

Default values are what you will be presented with when you display an empty form.

Get all values using $form->getDefaults() or a single value using $form->getDefault($name).

Record values, which are merged with the default values, are displayed when a Doctrine record is associated with the form.

Get all values using $form->getDefaults() or a single value using $form->getDefault($name).

Original POST values are displayed when the form validation failed.

Get all values using $form->getTaintedValues().

Clean POST values are the ones that have been validated and transformed by the form validators. At that point, you will most likely choose to save the form and redirect.

Get all values using $form->getValues() or a single value using $form->getValue($name).

Get all values regardless of origin

In one scenario, I needed to access the form's values to inject them into Javascript. There is a method to extract a value as it will appear in the HTML, without worrying about whether it's default, record, dirty  POST or clean POST.

Get the value directly from the field using $form->offsetGet($name)->getValue(). Alternatively, you can use $form[$name]->getValue() which will yield the same result.

Previous: Their Programming Language Sucks! Next: Profiling JS Applications