我有个问题。我需要验证一个不在表单类型类实体中的字段。以前我用过这个代码:
$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
已被弃用。有人知道我应该用什么代替吗?
我是这样做的:
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'))
接口FormValidatorInterface
已弃用,将在Symfony 2.3中删除。
如果您使用此接口实现了自定义验证器,则可以用收听
FormEvents::POST_BIND
(或*BIND
事件中的任何其它事件)。万一您使用了CallbackValidator类,现在应该传递回调直接连接到CCD_ 6。
通过https://github.com/symfony/symfony/blob/master/UPGRADE-2.1.md#deprecations
对于其他寻求帮助将验证器更改为事件订阅者的人(因为它与普通订阅者略有不同),请遵循以下内容:
步骤1
更改:
$builder->addValidator(new AddNameFieldValidator());
至$builder->addEventSubscriber(new AddNameFieldSubscriber());
步骤2
将验证器类(以及所有命名空间)替换为订阅者类。您的订阅者类应该如下所示:
// 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-form-class