问题
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:
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.
Used a
NotNull
validator because the default value ofmealSchema
wasnull
, not an empty array.
来源:https://stackoverflow.com/questions/35766535/symfony2-choice-field-validation-not-working