7

我有个问题。我需要验证表单类型类中不在实体中的字段。以前我使用过这段代码:

$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'));
    }
}))

但由于 Symfony 2.1 方法addValidator和类CallbackValidator已被弃用。有谁知道我应该改用什么?

4

3 回答 3

10

我是这样做的:

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'))
于 2013-03-21T09:12:45.953 回答
2

该接口FormValidatorInterface已被弃用,将在 Symfony 2.3 中删除。

FormEvents::POST_BIND如果您使用此接口实现了自定义验证器,则可以用侦听(或任何其他事件)的事件侦听器替换它们 *BIND。如果您使用了 CallbackValidator 类,您现在应该将回调直接传递给addEventListener.

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

于 2012-07-26T12:13:26.697 回答
2

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

于 2013-06-05T09:51:58.637 回答