Symfony2 Choice字段验证无效

时间:2016-03-03 08:10:37

标签: 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, 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

1 个答案:

答案 0 :(得分:1)

好的,我解决了。

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

我的同事想要模仿MySQL&#34; SET&#34; Doctrine中的字段类型,所以他使用数组作为入口点值,并在setter方法中将其转换为位值(在getter方法中反过来)。

这就是选择相关验证规则没有奏效的原因。目前,我已经制定了两个快速解决方案:

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

  2. 使用NotNull验证程序,因为mealSchema的默认值为null,而不是空数组。

相关问题