Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deprecated method addValidation and class CallbackValidator in Symfony2

I have a problem. I need to validate a field that is not in entity in form type class. Previously I used this code:

$builder->addValidator(new CallbackValidator(function(FormInterface $form){
    if (!$form['t_and_c']->getData()) {
        $form->addError(new FormError('Please accept the terms and conditions in order to registe'));
    }
}))

But since Symfony 2.1 method addValidator and class CallbackValidator are deprecated. Does anyone know what I should use instead?

like image 248
Paul Seleznev Avatar asked Jul 26 '12 11:07

Paul Seleznev


3 Answers

I've done it in this way:

add('t_and_c', 'checkbox', array(
            'property_path' => false,
            'constraints' => new True(array('message' => 'Please accept the terms and conditions in order to register')),
            'label' => 'I agree'))
like image 124
Paul Seleznev Avatar answered Nov 20 '22 15:11

Paul Seleznev


The interface FormValidatorInterface was deprecated and will be removed in Symfony 2.3.

If you implemented custom validators using this interface, you can substitute them by event listeners listening to the FormEvents::POST_BIND (or any other of the *BIND events). In case you used the CallbackValidator class, you should now pass the callback directly to addEventListener.

via https://github.com/symfony/symfony/blob/master/UPGRADE-2.1.md#deprecations

like image 35
Koc Avatar answered Nov 20 '22 14:11

Koc


For anyone else looking for help changing their validators to event subscribers (as it is slightly different to normal subscribers) follow this:

Step 1

Change:

$builder->addValidator(new AddNameFieldValidator());
to
$builder->addEventSubscriber(new AddNameFieldSubscriber());

Step 2

Replace your validator class (and all the namespaces) to a subscriber class. Your subscriber class should look like the following:

// src/Acme/DemoBundle/Form/EventListener/AddNameFieldSubscriber.php
namespace Acme\DemoBundle\Form\EventListener;

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormError;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class AddNameFieldSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(FormEvents::POST_BIND => 'postBind');
    }

    public function postBind(FormEvent $event)
    {
        $data = $event->getData();
        $form = $event->getForm();

        $form->addError(new FormError('oh poop'))
    }
}

You do not need to register the subscriber in a service file (yml or otherwise)


Reference: http://symfony.com/doc/2.2/cookbook/form/dynamic_form_modification.html#adding-an-event-subscriber-to-a-form-class

like image 2
Andrew Atkinson Avatar answered Nov 20 '22 14:11

Andrew Atkinson