Symfony2 Choice field validation not working

断了今生、忘了曾经 提交于 2019-12-20 05:09:06

问题


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

    // ...
}

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

回答1:


Ok, I solved it.

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.

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:

  1. 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.

  2. Used a NotNull validator because the default value of mealSchema was null, not an empty array.



来源:https://stackoverflow.com/questions/35766535/symfony2-choice-field-validation-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!