How can I add a violation to a collection?

Steve picture Steve · Jul 30, 2012 · Viewed 8.4k times · Source

My form looks like this:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $factory = $builder->getFormFactory();

    $builder->add('name');

    $builder->add('description');

    $builder->add('manufacturers', null, array(
        'required' => false
    ));

    $builder->add('departments', 'collection', array(
        'type' => new Department
    ));
}

I have a class validator on the entity the form represents which calls:

    if (!$valid) {
        $this->context->addViolationAtSubPath('departments', $constraint->message);
    }

Which will only add a 'global' error to the form, not an error at the sub path. I assume this is because departments is a collection embedding another FormType.

If I changed departments to one of the other fields it works fine.

How can I get this error to appear in the right place? I assume it would work fine if my error was on a single entity within the collection, and thus rendered in the child form, but my criteria is that the violation occur if none of the entities in the collection are marked as active, thus it needs to be at the parent level.

Answer

Bernhard Schussek picture Bernhard Schussek · Jul 31, 2012

By default, forms have the option "error_bubbling" set to true, which causes the behavior you just described. You can turn off this option for individual forms if you want them to keep their errors.

$builder->add('departments', 'collection', array(
    'type' => new Department,
    'error_bubbling' => false,
));