Symfony2 无法实例化接口 Doctrine\Common\Collections\Collection

问题描述 投票:0回答:1

Symfony 版本 2.8

当我尝试添加 new Collection() 时遇到问题;在用户实体的构造函数中。

public function __construct()
{ 
    $this->sectors = new Collection();
    parent::__construct();
}

部门具有多对多关系

/**
 * @ORM\ManyToMany(targetEntity="UserBundle\Entity\Sectors", fetch="EAGER")
 * @ORM\JoinTable(
 *      joinColumns={@ORM\JoinColumn(onDelete="CASCADE")},
 *      inverseJoinColumns={@ORM\JoinColumn(onDelete="CASCADE")}
 * )
 */
public $sectors;

getter/setter 方法是

    /**
 * Add sector
 *
 * @param UserBundle\Entity\Sectors $sector
 *
 * @return User
 */
public function addSector(UserBundle\Entity\Sectors $sector)
{
    $this->sectors[] = $sector;

    return $this;
}

/**
 * Remove sector
 *
 * @param UserBundle\Entity\Sectors $sector
 */
public function removeSector(UserBundle\Entity\Sectors $sector)
{
    $this->sectors->removeElement($sector);
}

/**
 * Get sectors
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getSectors()
{
    return $this->sectors;
}

当我使用 FormType 时:

     $builder
     ->add('sectors', EntityType::class, array(
            'class'       => 'UserBundle\Entity\Sectors',
            'placeholder' => 'Select Sector ...',
            'label' => 'Sector',
            'required' => false,
            'attr' => ['placeholder' => 'Select Sector ...', 'data-jcf' => '{"wrapNative": false, "wrapNativeOnMobile": false, "useCustomScroll": true, "multipleCompactStyle": true}'],
            'multiple' => true,
            'expanded' => false,
            'query_builder' => function(EntityRepository $er) {
                return $er->createQueryBuilder('u')
                    ->orderBy('u.name', 'ASC');
            },
        ));
$formModify = function (FormInterface $form, \Doctrine\Common\Collections\ArrayCollection $sector, $factory) {

$output = [];
foreach($sector as $sec) {
    $output[] = $sec->id;
}
$formOption = array( 
       'class' => 'UserBundle\Entity\UserAccreditation',
       'multiple' => true,
       'auto_initialize' => false,
       'required' => false,
       'expanded' => true,
       'choice_attr' => function ($output) {
             return ['class' => 'attr_checkbox'];
        },
       'query_builder' => function(EntityRepository $ertt) use ($output) {
        $qb = $ertt->createQueryBuilder('g');
        $qb->select(array('g'));
        $qb->where('g.sector IN (:sector_id)');
        $qb->setParameters( array('sector_id' => $output) );
        $qb->orderBy('g.name', 'ASC');
        return $qb;
      },
      );
      $form->add($factory->createNamed('accreditationdata', EntityType::class, null, $formOption));
            };

      $builder->addEventListener(FormEvents::PRE_SET_DATA,function (FormEvent $event) use ($formModify,$factory) {
                    $data = $event->getData();
                    $form = $event->getForm();

                    if ($data != null) {
                        //print_r(get_object_vars($data->getSectors()));
                        $formModify($event->getForm(), $data->getSectors(),$factory);
                    }
                }
            );

            $factory = $builder->getFormFactory();
            $builder->get('sectors')->addEventListener(FormEvents::POST_SUBMIT,function (FormEvent $event) use ($formModify,$factory) {
                    $sector = $event->getForm()->getData();
                    //print_r($sector);
                    $formModify($event->getForm()->getParent(), $sector,$factory);
                }
            );

我收到以下错误:

致命错误:无法实例化接口 Doctrine\Common\Collections\Collection

之前我使用 ArrayCollection 而不是 Collection,我必须这样做,因为我收到错误

类型错误:传递给 UserBundle\Form\Type\ProfileAboutMeFormType::UserBundle\Form\Type{closure}() 的参数 2 必须是 Doctrine\Common\Collections\ArrayCollection 的实例,给定的 Doctrine\ORM\PersistentCollection 实例,

通过谷歌搜索,我在 github 链接上找到了这个解决方案

https://github.com/doctrine/orm/issues/5946

但我仍然面临着这个问题。谁能告诉我这里出了什么问题吗?

collections symfony-2.8
1个回答
0
投票

您应该将 $sector 的变量类型声明为 Collection,但是构造函数应该为 $sector 分配一个新的 ArrayCollection。

不要忘记包括两种用途。

    use Doctrine\Common\Collections\ArrayCollection;
    use Doctrine\Common\Collections\Collection;

    /**
     * @ORM\ManyToMany(targetEntity="UserBundle\Entity\Sectors", fetch="EAGER")
     * @ORM\JoinTable(
     *      joinColumns={@ORM\JoinColumn(onDelete="CASCADE")},
     *      inverseJoinColumns={@ORM\JoinColumn(onDelete="CASCADE")}
     * )
     */
    private Collection $sector ;

    public function __construct()
    {
        $this->sector = new ArrayCollection();
    }
© www.soinside.com 2019 - 2024. All rights reserved.