forms - 删除来自空集合表单项的空值

标签 forms symfony collections null

我正在尝试以 2 个实体(例如,Product 和 Category 来制作 simpe)之间的形式实现多对多关系,并使用文档中描述的带有原型(prototype)和 javascript ( http://symfony.com/doc/current/cookbook/form/form_collections.html ) 的方法。

这是创建类别集合的 ProductType 行:

$builder->add('categories', 'collection', array(
                   'type' => 'entity',
                   'options' => array(
                        'class' => 'AppBundle:Category',
                        'property'=>'name',
                        'empty_value' => 'Select a category',
                        'required' => false),
                   'allow_add' => true,
                   'allow_delete' => true,
              ));

当我有一个新项目时,一个新的选择出现设置为空值“选择一个类别”。问题是,如果我不更改空值,它会被发送到服务器,并且在 $form->bind() 之后,我的 Product 对象会在 $category ArrayCollection 中获得一些空值。

虽然我首先要测试 Product 实体中的 setter 中的值,并在 ProductType 中添加 'by_reference'=>false,但在这种情况下我得到一个异常,指出 null 不是 Category 的实例。

如何确保忽略空值?

最佳答案

引用 documentation关于“delete_empty”:

If you want to explicitly remove entirely empty collection entries from your form you have to set this option to true

$builder->add('categories', 'collection', array(
               'type' => 'entity',
               'options' => array(
                    'class' => 'AppBundle:Category',
                    'property'=>'name',
                    'empty_value' => 'Select a category'),
               'allow_add' => true,
               'allow_delete' => true,
               'delete_empty' => true
          ));

由于您使用嵌入式表单,您可能会遇到一些问题,例如 Warning: spl_object_hash() expects parameter 1 to be object, null given when passing empty collections。

按照此 answer 中的说明删除 required=>false对我不起作用。

引用了类似的问题 here在 github 上并由 PR 9773 解决

关于forms - 删除来自空集合表单项的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17653294/

相关文章:

javascript - JS 在单击提交时验证表单

php - 如何将自定义选项传递给 Symfony 表单

collections - 扩展 VecDeque 以限制大小

java - 如何创建根据列表的自然顺序排序的 PQ?

php - 当数据来自多个表时,如何使用 PHP 和 MYSQL 填充表单中的字段?

html - 单击时不一致的表单中的 CSS 文本?

css - Symfony2 : background color of date widget

php - 根据另一个实体字段值查询一个实体

php - 无法测试 Symfony2 控制台命令

java - ConcurrentHashMap 中的故障安全迭代器