【问题标题】:Symfony2 Choice field validation not workingSymfony2 选择字段验证不起作用
【发布时间】:2016-03-03 08:10:37
【问题描述】:

我在 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

【问题讨论】:

  • stackoverflow.com/questions/19818548/… 这看起来很有希望,但看起来有很多不必要的工作。
  • 验证中的属性名称应与表单中的字段名称相同 (mealSchema !== meal_schema)。

标签: php forms validation symfony choice


【解决方案1】:

好的,我解决了。

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

我的同事想在 Doctrine 中模拟 MySQL“SET”字段类型,因此他使用数组作为入口点值,并在 setter 方法中将其转换为位值(在 getter 方法中反之亦然)。

这就是为什么与选择相关的验证规则都不起作用的原因。目前,我制定了 2 个快速解决方案:

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

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

【讨论】:

    猜你喜欢
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多