Home » Php » php – Deprecated method addValidation and class CallbackValidator in Symfony2

php – Deprecated method addValidation and class CallbackValidator in Symfony2

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&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'))

Answer:

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

Answer:

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