我正在尝试以2个实体(例如,要创建simpe的Product和Category)之间的形式实现ManyToMany关系,并使用带有原型和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的实例。
如何确定空值被忽略?
最佳答案
在'delete_empty'上引用documentation:
如果要从表单中显式删除完全为空的集合条目,则必须将此选项设置为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
之类的问题。按照此answer的说明删除
required=>false
对我不起作用。github上引用了类似的问题here,并由PR 9773解决了