Symfony Form EventListeners

Frequently when coding forms, there is a constraint or a field that becomes *required depending on the value of a select field. For this and many more user cases, symfony has the Form Event Listeners that are design specifically for that cases.

So if you want to do get the Request in the form to inject it in some custom Constraint, then this is the incorrect way to do it:

public function buildForm(FormBuilderInterface $builder, array $options) {

$request = Request::createFromGlobals();
$request = $request->request->get('MyBundle');
$type = is_null($request['type']) ? $options['data']->getType() : $request['type'];

$builder->add('myDate', 'datetime', array(
'constraint' => array ( new fieldConstraint (array('type' => $type )) )
);

}

The Symfony approach using Form event listeners looks more like:

</pre>
<pre>    public function onPreSubmit(FormEvent $event)
    {
        $form = $event->getForm();
        $data = $event->getData();
// Note that at this point $data comes from POST
        if ($data['type'] === 'sometype') {
// Then we re-declare the form element adding the constraint (And any other needed stuff)
            $form->add('myDate', 'datetime',
                array(
                    'constraints' => array(
                        new fieldConstraint()
                    )
                )
            );
        }
 }

This looks at least more elegant and readable than trying to access the Request from the formType itself.

And the lesson learnt is:
If you feel that you are trying to access a value in a strange, non straight-forward way, then stop and take some time to research. For sure there is an easier way to do it ;)


Create a website or blog at WordPress.com

%d bloggers like this: