Как исправить аргумент 1, переданный в экземпляр Bundle\Entity\.., указанный экземпляр Doctrine\Common\Collections\ArrayCollection?

Я пытаюсь создать модуль, в котором при создании нового вопроса я назначаю его разным областям, поэтому я думаю, что это должно быть отношение «многие ко многим» и получить другую таблицу «FSA_AreasQuestions», но я не могу получить ее. работать еще.

На самом деле у меня есть 3 таблицы:
-FSA_Questions
-FSA_Areas
-FSA_AreasQuestions

Вот как я это делаю:

Сущность FsaAreas:

  class FsaAreas
{

     /**
         * @var \Doctrine\Common\Collections\Collection
         * @ORM\ManyToMany(targetEntity="FsaQuestions", inversedBy="areas")
         * @ORM\JoinTable(name="fsa_areasquestions")
         */
        private $idQuestion;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->idQuestion = new \Doctrine\Common\Collections\ArrayCollection();
    }

 /**
     * Add idQuestion
     *
     * @param \FSABundle\Entity\FsaQuestions $idQuestion
     *
     * @return FsaAreas
     */
    public function addIdQuestion(\FSABundle\Entity\FsaQuestions $idQuestion)
    {
        $this->idQuestion[] = $idQuestion;

        return $this;
    }

    /**
     * Remove idQuestion
     *
     * @param \FSABundle\Entity\FsaQuestions $idQuestion
     */
    public function removeIdQuestion(\FSABundle\Entity\FsaQuestions $idQuestion)
    {
        $this->idQuestion->removeElement($idQuestion);
    }

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

}

Сущность FsaQuestions:

class FsaQuestions
{
 /**
     *  @ORM\ManyToMany(targetEntity="FsaAreas", inversedBy="idQuestion")
     */
    private $areas;

    /**
     * Constructor
     */
    public function __construct()
    {
       $this->areas = new \Doctrine\Common\Collections\ArrayCollection;
    }

 /**
     * Add Areas
     * @param \FSABundle\Entity\FsaAreas $area
     * 
     * @return FsaQuestions
     */
    public function addArea(\FSABundle\Entity\FsaAreas $area){
        $this->areas[] = $area;
        return $this;
    }


    /**
     * Remove Areas
     * @param \FSABundle\Entity\FsaAreas $area
     */
    public function removeArea(\FSABundle\Entity\FsaAreas $area){
        $this->areas->removeElement($area);
    }

    /**
     * Get Areas
     * @return \Doctrine\Common\Collections\ArrayCollection;
     */
    public function getAreas(){
        return $this->areas;
    }
}

В конце, когда я выполняю некоторые тесты, я получаю эту ошибку: Catchable Fatal Error: аргумент 1, переданный в FSABundle\Entity\FsaQuestions::addIdArea(), должен быть экземпляром FSABundle\Entity\FsaAreas, экземпляром Doctrine\Common\Collections\ArrayCollection задано


Это моя форма (FsaQuestionsType):

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('title',TextType::class, array(
            "required"=>"required",
            "attr"=>array(
            "class"=>"form-control form-control-title"
        )))
        ->add('explanation',TextType::class, array(
            "required"=>"required",
            "attr"=>array(
            "class"=>"form-control form-control-explanation"
        )))
        ->add('question',TextType::class, array(
            "required"=>"required",
            "attr"=>array(
            "class"=>"form-control form-control-question"
        )))
        ->add('reactionplan',TextareaType::class, array(
            "required"=>"required",
            "attr"=>array(
            "class"=>"form-control form-control-reactionPLan"
        )))
        ->add('status','Symfony\Component\Form\Extension\Core\Type\CheckboxType', array(
            "label"=>"Enabled:",
            "required"=>false
            ))
        // ->add('usrcreate')
        // ->add('usrupdate')
        // ->add('datecreate')
        // ->add('dateupdate')
        ->add('idCategory',EntityType::class,array(
            "class"=>"FSABundle:FsaCategories",
            'choice_label' => 'name',
            "attr"=>array("class"=>"form-control"
            )))
        ->add('areas',EntityType::class,array(
            "class"=>"FSABundle:FsaAreas",
            'choice_label' => 'name',
            'expanded' =>false,
            'multiple' =>true,
            // 'allow_add' => true,
            // 'by_reference' => false,
            "attr"=>array("class"=>"form-control"
            )))
        ;
    }

Любой совет? или что не так?


person Irving Soto Guzman    schedule 20.08.2019    source источник


Ответы (1)


Простой рабочий пример

class Tag
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\ManyToMany(targetEntity="Post", mappedBy="tags")
     */
    private $posts;

    public function __construct()
    {
        $this->posts = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getPosts()
    {
        return $this->posts;
    }
}

class Post
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\ManyToMany(targetEntity="Tag", inversedBy="posts")
     * @ORM\JoinTable(name="tags_posts")
     */
    private $tags;

    public function __construct()
    {
        $this->tags = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getTags()
    {
        return $this->tags;
    }

    public function addTag(Tag $tag): self
    {
        if (!$this->tags->contains($tag)) {
            $this->tags->add($tag);
        }

        return $this;
    }
}

class PostType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class)
            ->add('tags', EntityType::class, [
                'class' => Tag::class,
                'choice_label' => 'name',
                'multiple' => true,
                'expanded' =>false,
            ])
            ->setMethod('POST')
            ->add('save', SubmitType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Post::class,
        ));
    }
}
person Ihor Kostrov    schedule 20.08.2019
comment
Извините, но я получаю сообщение об ошибке, что параметр allow_add не существует. - person Irving Soto Guzman; 20.08.2019
comment
Конечно, я отредактировал свой вопрос, добавив тип формы, спасибо. - person Irving Soto Guzman; 20.08.2019
comment
Измените EntityType на CollectionType - person Ihor Kostrov; 20.08.2019
comment
Но если я изменю его на тип коллекции, он не будет отображать области в выбранном - person Irving Soto Guzman; 20.08.2019
comment
Вы добавили опцию entry_type? - person Ihor Kostrov; 20.08.2019
comment
entry_type должен быть таким?: -›add('idArea',CollectionType::class,[ entry_type=›[ EntityType::class, class=›FSABundle:FsaAreas, 'choice_label' =› 'name', 'expanded' =›false, 'multiple' =›true, ], attr=›array(class=›form-control) ]) - person Irving Soto Guzman; 20.08.2019
comment
Вы правы, здесь нужно использовать EntityType, но я не могу воспроизвести вашу проблему. Я могу обновить свой ответ простым рабочим примером, если вам нужно. - person Ihor Kostrov; 20.08.2019
comment
Я был бы очень признателен, даже если бы вы могли сделать это с помощью простого примера отношений «многие ко многим», спасибо. - person Irving Soto Guzman; 20.08.2019
comment
Обновленный ответ с примером - person Ihor Kostrov; 21.08.2019