【问题标题】:Deprecated method addValidation and class CallbackValidator in Symfony2Symfony2 中不推荐使用的方法 addValidation 和类 CallbackValidator
【发布时间】:2013-08-28 18:53:18
【问题描述】:

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

$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 已被弃用。有谁知道我应该改用什么?

【问题讨论】:

  • CallbackValidator 并没有被弃用,事实上,它是tagged as @api

标签: php symfony-2.1


【解决方案1】:

我是这样做的:

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'))

【讨论】:

  • 太棒了!感谢您发布此消息!
  • 使用 Symfony\Component\Validator\Constraints\True;
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    对于其他寻求帮助的人,将他们的验证器更改为事件订阅者(因为它与普通订阅者略有不同),请遵循以下步骤:

    步骤 1

    变化:

    $builder->addValidator(new AddNameFieldValidator());

    $builder->addEventSubscriber(new AddNameFieldSubscriber());

    第二步

    将您的验证器类(以及所有命名空间)替换为订阅者类。 您的订阅者类应如下所示:

    // 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'))
        }
    }
    

    您无需在服务文件(yml 或其他)中注册订阅者


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

    【讨论】:

    猜你喜欢
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 2019-10-13
    相关资源
    最近更新 更多