Symfony Form: Extract Values

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.

2 thoughts on “Symfony Form: Extract Values

  1. what about $form[$name]->getValue() ?

  2. @Massimiliano Arione Right, the square brackets use the underlying offsetGet() method as required by the ArrayAccess interface, and so will be synonymous. The idea here is to get the widget and then its value, rather than the form’s getValue() method which does not always get the most current value, or might return nothing in case validation fails. I’ll add a note regarding that in the post.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">