如何向集合添加违规行为? [英] How can I add a violation to a collection?

查看:41
本文介绍了如何向集合添加违规行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单如下所示:

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);
    }

这只会在表单中添加全局"错误,而不是在子路径中添加错误.我认为这是因为部门是一个嵌入另一个 FormType 的集合.

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.

如果我将 departments 更改为其他字段之一,它可以正常工作.

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.

推荐答案

默认情况下,表单将选项error_bubbling"设置为 true,这会导致您刚才描述的行为.如果您希望它们保留错误,您可以为单个表单关闭此选项.

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,
));

这篇关于如何向集合添加违规行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆