Add error to Symfony 2 form element

Alex Pliutau picture Alex Pliutau · Sep 14, 2012 · Viewed 65.6k times · Source

I check some validation in my controller. And I want to add error to specific element of my form on failure. My form:

use Symfony\Component\Form\FormError;

// ...

$config = new Config();
$form = $this->createFormBuilder($config)
        ->add('googleMapKey', 'text', array('label' => 'Google Map key'))
        ->add('locationRadius', 'text', array('label' => 'Location radius (km)'))
        ->getForm();

// ...

$form->addError(new FormError('error message'));

addError() method adds error to form, not to element. How can I add an error to locationRadius element?

Answer

Mun Mun Das picture Mun Mun Das · Sep 14, 2012

You can do

$form->get('locationRadius')->addError(new FormError('error message'));

As form elements are also of FormInterface type.