我尝试pu multiplie =>错误的多关系,但我有这个错误。
Expected an object, but got a collection. Did you forget to pass
“multiple = true”到实体字段?
所以我找到了解决方案,但我还有其他错误。
Catchable Fatal Error: Argument 1 passed to Plop\PlipBundle\Form\{closure}() must be an instance of Plop\PlipBundle\Form\Collection, null given in /var/www/Symfony/src/plop/plipBundle/Form/CampaignSupportType.php line 22
是我的代码:
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add(
$builder->create('supports', 'entity', array(
'class' => 'PlopPlipBundle:Support','multiple' => false,
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('s')
->orderBy('s.name', 'ASC');
}, 'property' => 'name'))
->prependNormTransformer(new CallbackTransformer(
// transform the collection to its first element
function (Collection $coll) { return $coll[0]; },
// transform the element to a collection
function (MyEntity $entity) { return new ArrayCollection(array($entity)); }
))
);
}
修改
在@bernhard的回答中,我收到了一个新错误:
Catchable Fatal Error: Argument 1 passed to Plop\PlipBundle\Form\{closure}() must be an instance of Plop\PlipBundle\Form\Collection, instance of Doctrine\Common\Collections\ArrayCollection given in /var/www/Symfony/src/plop/PlipBundle/Form/CampaignSupportType.php line 22
现在不是null,但Doctrine\Common\Collections\ArrayCollection
和Symfony2等待Plop\PlipBundle\Form\Collection
。
答案 0 :(得分:2)
您应该将转换函数更改为接受null
,因为该字段可能为空或未选中。
->prependNormTransformer(new CallbackTransformer(
// transform the collection to its first element
function (Collection $coll = null) {
return $coll ? $coll[0] : null;
},
// transform the element to a collection
function (MyEntity $entity = null) {
return new ArrayCollection($entity ? array($entity) : array());
}
))
那么你的代码应该可以正常工作。