我在Symfony 2.7.10中有一个表单,其定义如下所示:
<?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文件中的外观:
My'Real'Namespace'Entity'Recipe:
properties:
name:
- NotBlank: ~
mealSchema:
# Look below
名称字段验证有效,但 mealSchema 验证无效。我已经尝试过但没有成功的设置:
# 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
好的,我解决了。
我的错误是在堆栈溢出上询问时没有提供有关mealSchema
实体中字段的信息。如果我这样做,那么我会意识到实体字段实际上是一个smallint
。
我的同事想在 Doctrine 中模拟 MySQL"SET"字段类型,因此他使用数组作为入口点值,并在 setter 方法中将其转换为位值(在 getter 方法中则相反)。
这就是为什么与选择相关的验证规则都不起作用的原因。现在,我做了2个快速解决方案:
-
将 RecipeType 中所有字段的名称从下划线更改为驼峰大小写,因为这就是它们在我们的实体中的命名方式。这有助于将错误附加到表单而不是字段。
-
使用了
NotNull
验证器,因为默认值mealSchema
是null
,而不是空数组。