0

我尝试 pu a multiplie => false to a manytomany 关系,但我有这个错误。

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\ArrayCollectionSymfony2 等待一个Plop\PlipBundle\Form\Collection.

4

1 回答 1

2

您应该将转换函数更改为 accept 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());
    }
))

那么你的代码应该可以正常工作。

于 2012-08-09T20:12:37.673 回答