[英]Symfony 4 : get the error message from count constraint applied on collection type
I am using a collection type of symfony 4, and i wish to apply a count constraint to this collection.我正在使用 symfony 4 的集合类型,我希望对这个集合应用计数约束。
I have followed this tutorial: https://symfony.com/doc/current/form/form_collections.html我遵循了本教程: https://symfony.com/doc/current/form/form_collections.html
My idea is to apply the constraint directly on the collection:我的想法是将约束直接应用于集合:
$builder
->add('tags', CollectionType::class, [
'entry_type' => Tag::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'by_reference' => false,
'constraints' => [
new Assert\Count(['min' => 1, 'max' => 3])
]
])
;
But this does not work: I do not get any error message...但这不起作用:我没有收到任何错误消息......
I have also try to use this constraint directly in the entity Task
, without success.我也尝试在实体
Task
中直接使用此约束,但没有成功。
So how can I get the error message from count constraint applied on collection type?那么如何从应用于集合类型的计数约束中获取错误消息?
As @emix said in comment正如@emix 在评论中所说
With NotNull you tell the validator the field cannot be empty.
使用 NotNull,您可以告诉验证器该字段不能为空。 Using the Count validator you limit the collection's size (using the min/max or both)
使用 Count 验证器可以限制集合的大小(使用最小/最大或两者)
And to print the error I set the parameter error_bubbling
to false
of the CollectionType
.为了打印错误,我将
CollectionType
的参数error_bubbling
设置为false
。
If you are using doctrine annotations, I think you can proceed like this:如果您使用的是 doctrine 注释,我认为您可以这样进行:
Do not pass the constraint in the form builder.不要在表单生成器中传递约束。 I would have added the constraint in the entity where you stored the tags.
我会在您存储标签的实体中添加约束。
Something like this像这样的东西
/**
* @Assert\Count(
* min = 1,
* max = 5,
* minMessage = "You must specify at least one Tag",
* maxMessage = "You cannot specify more than 5 tags"
* )
*/
protected $tags;
If this isn't stored in any entity, you might want to handle the assertion by yourself in the controller dealing with your form action.如果这没有存储在任何实体中,您可能希望在处理表单操作的 controller 中自己处理断言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.