validation on unbound form field

symfony-2.1

Solution

Edit :

I've just made a more complete answer on topic Symfony validate form with mapped false form fields

Original answer

Validating unbound (non mapped) field in a form is not well documented and the fast evolving form and validator components make the few examples obsoletes (for Symfony 2.1.2).

For now I succeed in validated non mapped fields with event listener. Here is my simplified code :

namespace Dj\TestBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Symfony\Component\Form\FormEvents;
use Dj\TestBundle\Form\EventListener\NewPostListener;

class PostType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('lineNumber', 'choice', array(
                        'label' => 'How many lines :',
                        'choices' => array(
                            3 => '3 lines',
                            6 => '6 lines'
                        ),
                        // 'data' => 3, // default value
                        'expanded' => true,
                        'mapped' => false
                    ))
                ->add('body', 'textarea', array(
                        'label' => 'Your text',
                        'max_length' => 120));

        // this listener will validate form datas
        $listener = new NewPostListener;
        $builder->addEventListener(FormEvents::POST_BIND, array($listener, 'postBind'));
    }

    // ... other methods
}

And the event listener :

namespace Dj\TestBundle\Form\EventListener;

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormError;

/**
 * listener used at Post creation time to validate non mapped fields
 */
class NewPostListener
{

    /**
     * Validates lineNumber and body length
     * @param \Symfony\Component\Form\FormEvent $event
     */
    public function postBind(FormEvent $event)
    {
        $form = $event->getForm();
        $data = $event->getData();

        if (!isset($data->lineNumber)) {
            $msg = 'Please give a correct line number';
            $form->get('lineNumber')->addError(new FormError($msg));
        }
        
        // ... other validations

    }
}

This is how I validate my non mapped fields until I find out how to do this with validators.

Problem

I have a form with an extra unbound field added using 'property_path' => false. I would like to have a simple validation on this field and I've found many answers that suggest to use something like ``` $builder->addValidator(...); ``` but I've seen that in symfony 2.1 $builder->addValidator is deprecated. Does anyone know what is the correct way to put a validation on an unbound field in Symfony 2.1?

Original source

Related problems