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?
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'))
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 toaddEventListener
.
via https://github.com/symfony/symfony/blob/master/UPGRADE-2.1.md#deprecations
For anyone else looking for help changing their validators to event subscribers (as it is slightly different to normal subscribers) follow this:
Change:
$builder->addValidator(new AddNameFieldValidator());
to$builder->addEventSubscriber(new AddNameFieldSubscriber());
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With