Php Symfony2选择字段验证不起作用

Php Symfony2选择字段验证不起作用,php,forms,validation,symfony,choice,Php,Forms,Validation,Symfony,Choice,我在Symfony 2.7.10中有一个表格,其定义如下: <?php // ... class RecipeType extends AbstractType { // ... /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder,

我在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,
        ])
     }

    // ...
}
名称字段验证有效,但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
好的,我解决了

我的错误是,在询问stackoverflow时,没有提供实体中有关
mealSchema
字段的信息。如果我这样做,我就会意识到,实体字段实际上是一个
smallint

我的同事想在条令中模拟MySQL“SET”字段类型,所以他使用数组作为入口点值,并在setter方法中将其转换为位值(在getter方法中则相反)

这就是为什么选择相关的验证规则都不起作用。目前,我有两个快速解决方案:

  • 将RecipeType中所有字段的名称从下划线更改为camelCase,因为在实体中它们是这样命名的。这有助于将错误附加到表单而不是字段

  • 使用了
    NotNull
    验证器,因为
    mealSchema
    的默认值是
    null
    ,而不是空数组


  • 这看起来很有希望,但看起来有很多不必要的工作。验证中的属性名应该与表单中的字段名相同(
    mealSchema!==mean\u schema
    )。
    # 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