假设我有以下表单构建器buildForm方法:
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(
'travelTime',
'datetime',
array(
'label' => 'Time',
'date_widget' => 'single_text',
'time_widget' => 'single_text',
'invalid_message' => 'Please enter a valid date and time',
)
)
->add(
'acmeEntity',
'entity',
array(
'label' => 'Acme Entity:',
'class' => 'AcmeBundle:MyEntity',
'expanded' => false,
'multiple' => false,
)
)
}
如何覆盖(或删除)“acmeEntity'”的验证?表单字段(并且只有该字段),以便在我调用时:
$form->handleRequest($request);
$form->isValid();
在Controller中,acmeEntity将不会包含在确定$form->isValid()
是否返回true的验证中?我已尝试将constraints => false
添加到字段选项中,但我收到此错误消息:
Notice: Trying to get property of non-object in /var/www/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php line 67
有没有人知道为Symfony表单字段禁用服务器端验证的正确方法?
编辑:
请注意,我不是在寻找如何完全禁用验证。这可以通过添加:
来完成 // Disable form validation
$builder->addEventListener(FormEvents::POST_SUBMIT, function ($event) {
$event->stopPropagation();
}, 900); // Always set a higher priority than ValidationListener
到表单构建器的底部。
相反,我想知道如何完全禁用单个表单字段的验证。谢谢大家和好的狩猎!
答案 0 :(得分:2)
您可以为您的实体定义custom form type并使用'validation_groups' => false
。这应该仅对此字段禁用验证。
自定义表单类型可能如下所示:
// .../Your/OwnBundle/Form/Type/AcmeEntityType.php
namespace Acme\DemoBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class AcmeEntityType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'validation_groups' => false
));
}
public function getParent()
{
return 'entity';
}
public function getName()
{
return 'acme_entity';
}
}
然后您可以使用:
$builder
->add(
'travelTime',
'datetime',
array(
'label' => 'Time',
'date_widget' => 'single_text',
'time_widget' => 'single_text',
'invalid_message' => 'Please enter a valid date and time',
)
)
->add(
'acmeEntity',
'acme_entity',
array(
'label' => 'Acme Entity:',
'class' => 'AcmeBundle:MyEntity',
'expanded' => false,
'multiple' => false,
)
)
}
答案 1 :(得分:1)
我假设您从buildForm()
延长MyEntityType
致电AbstractType
,因此只需在您的类型中添加函数setDefaultOptions()
即可使用选项解析器,如symphony doc中所述{ {3}}
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'validation_groups' => false,
));
}
答案 2 :(得分:0)
你可以试试这个,我过去曾经用过它: