Symfony2 Choice字段验证不起作用 [英] Symfony2 Choice field validation not working
问题描述
我在Symfony 2.7.10中有一个表单,其定义如下所示:
I have a form in Symfony 2.7.10 which definition looks like this:
<?php
// ...
class RecipeType extends AbstractType
{
// ...
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add('meal_schema', 'choice', [
'label' => 'Mealtime schema',
'choices' => [
'breakfast' => 'Breakfast',
'second_breakfast' => 'Second breakfast',
'lunch' => 'Lunch',
'dinner' => 'Dinner',
'snack' => 'Snack',
'supper' => 'Supper',
],
'multiple' => true,
'expanded' => true,
'label_attr' => ['class' => 'col-md-2'],
'required' => true,
])
}
// ...
}
这是验证在validation.yml文件中的外观:
This is how validation looks in validation.yml file:
My\Real\Namespace\Entity\Recipe:
properties:
name:
- NotBlank: ~
mealSchema:
# Look below
名称字段验证有效,但餐式验证无效. 我已经尝试过但没有成功的设置:
Name field validation works, but mealSchema validation doesn't. Settings which I've already tried without success:
# This one works but assigns error to form instead of field so it's displayed on top of the page
- NotBlank:
message: Mealtime schema should not be blank
# This doesn't work
- Choice:
callback: [RecipeMealSchemaChoices, getChoiceKeys] # This method isn't even called
min: 1
minMessage: "Please select meal schema"
# This also doesn't work
- Count:
min: 1
max: 99
minMessage: Mealtime schema should not be blank
maxMessage: Max meal time exceeded
推荐答案
好,我解决了.
我的错误是在询问stackoverflow时不提供有关实体中mealSchema
字段的信息.如果这样做的话,我会意识到 entity字段实际上是smallint
.
My mistake was to not provide information about mealSchema
field in my entity when asking on stackoverflow. If I'd do that then I would realise that the entity field is in fact a smallint
.
我的同事想在Doctrine中模拟MySQL"SET"字段类型,因此他使用数组作为入口点值,并在setter方法中将其转换为位值(在getter方法中也是如此).
My colleague wanted to emulate a MySQL "SET" field type in Doctrine so he used an array as entrypoint values and converted it to bit values in setter method (and the other way around in the getter method).
这就是为什么与选择相关的验证规则均不起作用的原因.目前,我已经提出了两种快速解决方案:
That's why none of the choice-related validation rules worked. For now, I've made 2 quick solutions:
-
将RecipeType中所有字段的名称从下划线更改为camelCase,因为这是在我们实体中的命名方式.这有助于将错误附加到表单而不是字段.
Change all fields' names in RecipeType from underscore to camelCase because that is how they are named in our entity. This helped for the error being attached to the form instead of the field.
使用了NotNull
验证器,因为mealSchema
的默认值为null
,而不是空数组.
Used a NotNull
validator because the default value of mealSchema
was null
, not an empty array.
这篇关于Symfony2 Choice字段验证不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!