我正在尝试以 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
对我不起作用。
关于forms - 删除来自空集合表单项的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17653294/