我正在使用Symfony 2.6。我试图创建一个没有实体的表单,但得到以下错误:
选项"约束"不存在。已知的选项是:"动作", " attr"," auto_initialize"," block_name"," by_reference"," compound", " csrf_field_name"," csrf_message"," csrf_protection"," csrf_provider", " csrf_token_id"," csrf_token_manager"," data"," data_class", "禁用"," empty_data"," error_bubbling"," inherit_data", "意图","标签"," label_attr"," label_format","映射", " max_length","方法","模式"," post_max_size_message", " property_path"," read_only"," required"," translation_domain", "修剪","虚拟"。
class MessageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('sender', 'text', [
'constraints' => [
new Constraints\NotBlank(),
],
])
->add('recipient', 'email')
->add('message', 'textarea');
}
public function getName()
{
return 'message';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$collectionConstraint = new Constraints\Collection(array(
'fields' => [
'sender' => [
new Constraints\NotBlank(),
new Constraints\Email(),
],
'recipient' => [
new Constraints\NotBlank(),
new Constraints\Email(),
],
'message' => [
new Constraints\NotBlank(),
],
],
));
$resolver->setDefaults([
'validation_constraints' => $collectionConstraint,
]);
}
}
仅使用setDefaultOptions显示没有错误,但它不起作用,不验证字段。
可以看出,无论如何都试过了。我也尝试使用组件表单发件箱的文档,但得到相同的错误。
http://symfony.com/doc/current/components/form/introduction.html#form-validation
修改
我也尝试过这种方式并得到同样的错误。
$form = $formFactory->createBuilder()
->add('task', 'text', array(
'constraints' => new NotBlank(),
))
->add('dueDate', 'date', array(
'constraints' => array(
new NotBlank(),
new Type('\DateTime'),
)
))
->getForm();
答案 0 :(得分:0)
“约束”选项是ValidatorExtension
的一部分,它不是核心表格扩展的一部分。 TypeTestCase
仅加载核心表单扩展。添加以下代码可解决此问题。
protected function getExtensions()
{
return [new ValidatorExtension(Validation::createValidator())];
}
有关更多信息,https://symfony.com/doc/current/form/unit_testing.html#adding-custom-extensions
答案 1 :(得分:0)
这是一个很老的问题,我刚刚找到它,所以问题仍然会不时出现。
我在文档中确实喜欢: https://symfony.com/doc/current/components/form.html
$validator = Validation::createValidator();
$formFactory = Forms::createFormFactoryBuilder()
...
->addExtension(new ValidatorExtension($validator))
...
->getFormFactory();
并且不要忘记使用课程:
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;