问题
Hello I have a problem with collection of text fields in my form. When there are errors in one of the fields, these errors bubbles into parent form so they are not assigned to field but to parent itself. It is the 'points' collection in the following piece of code. I tried to set error_bubbling to false, but it has no effect.
<?php
namespace JamaLvova\AdminBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use JamaLvova\AdminBundle\Form\Type\ExercisePointsFormType;
class StartContestFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('startYear', 'hidden')
/*
some other form elements
*/
->add('points', 'collection', array(
'type' => 'text',
'allow_add' => true,
'label' => 'Body za jednotlivé úlohy:',
'error_bubbling' => false,
'options' => array(
'error_bubbling' => false,
'attr' => array("maxlength" => "4", "size" => "4")
)
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'JamaLvova\AdminBundle\Form\StartContestForm',
));
}
public function getName()
{
return 'startContestForm';
}
}
In StartContestForm I have $points property written like this:
/**
* @Assert\Type(type="integer", message="Hodnota {{ value }} není celé číslo.")
* @Assert\Range(
* min = "0",
* max = "",
* minMessage = "Body nemohou být záporné",
* maxMessage = "Příliš mnoho bodů"
* )
*/
private $points;
In twig template when I iterate over form.points, no field has errors, but form.points does. Does anyone have any idea where problem could be? Or am I missing something? Thanks a lot :-) (Symfony v. 2.1.4)
EDIT: It seems that if I use collection of forms ('type' => new PointsFormType()) instead of that 'type' => 'text', it somehow works as expected. Does it mean that I always need to use collection of forms to be able to assign errors to certain field?
回答1:
You may need to add cascade_validation' => true
$builder->add('startYear', 'hidden')
/*
some other form elements
*/
->add('points', 'collection', array(
'type' => 'text',
'allow_add' => true,
'label' => 'Body za jednotlivé úlohy:',
'error_bubbling' => false,
'cascade_validation' => true,
'attr' => array("maxlength" => "4", "size" => "4")
));
}
回答2:
Be careful because the cascade_validation attribute has been removed from Sf3 : http://symfony.com/doc/2.8/reference/forms/types/collection.html#cascade-validation
The cascade_validation option has been deprecated in Symfony 2.8 and will be removed in 3.0. Instead, use the Valid constraint in your model to cascade validation. Be aware of the fact that the validation_group option will not be considered for child forms.
来源:https://stackoverflow.com/questions/15621368/form-collection-error-bubbling