Kunwara
Kunwara

Reputation: 581

Doctrine assignment error: Cannot assign Doctrine\ORM\PersistentCollection to property

i have a upload from where i would like to show all the catégories from the database but i keep getting an error with the EntityType i don't know why was working before.

This is the error: Cannot assign Doctrine\ORM\PersistentCollection to property App\Entity\Category::$posts of type Doctrine\Common\Collections\ArrayCollection

<?php

declare(strict_types=1);

namespace App\Entity;

use App\Repository\CategoryRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=CategoryRepository::class)
 */
class Category
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private int $id;

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

    /**
     * @ORM\OneToMany(targetEntity=Post::class, mappedBy="Category_id")
     */
    private ArrayCollection $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;
    }

    /**
     * @return Collection|Post[]
     */
    public function gePosts(): Collection
    {
        return $this->posts;
    }

    public function addPost(Post $post): self
    {
        if (!$this->posts->contains($post)) {
            $this->$posts[] = $posts;
            $post->setCategoryId($this);
        }

        return $this;
    }

    public function removePost(Post $post): self
    {
        if ($this->posts->removeElement($post)) {
            // set the owning side to null (unless already changed)
            if ($post->getCategoryId() === $this) {
                $post->setCategoryId(null);
            }
        }

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

The upload Form where i am getting the error

<?php

declare(strict_types=1);

namespace App\Form\Post;

use App\Entity\Category;
use App\Entity\Post;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Constraints\NotBlank;

class UploadType extends AbstractType
{
    /**
     * @param \Symfony\Component\Form\FormBuilderInterface $builder
     * @param array                                        $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class, [
                
                'constraints' => [
                    new NotBlank([
                        'message' => 'Please enter a valid Title. '
                    ])
                ]
            ])
            ->add('category', EntityType::class, [
                'mapped' => false,
                'class' => Category::class,
                'choice_label' => 'name',
                'expanded' => true
            ])
            ->add('poster', FileType::class, [
                'required' => false,
                'constraints' => [
                    new File([
                        'maxSize' => '6000K',
                        'mimeTypes' => [
                            'image/x-png',
                            'image/jpeg',
                        ],
                        'mimeTypesMessage' => 'Please upload a image file.'
                    ])
                ]
            ])
            ->add('description', TextareaType::class, [
                'constraints' => [
                    new NotBlank([
                        'message' => 'Please enter a valid Title. '
                    ])
                ]
            ])
            ->add('mediainfo', TextareaType::class, [
                'required' => false,
            ]);
    }
    
    /**
     * @param \Symfony\Component\OptionsResolver\OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Post::class,
        ]);
    }
}

in the Post entity

   /**
     * @ORM\ManyToOne(targetEntity=Category::class, inversedBy="posts")
     */
    private Category $Category_id;

Environment info:

Upvotes: 18

Views: 17044

Answers (5)

Ali
Ali

Reputation: 286

In case this can help others, I had the same exact problem in my entity class. It turned out that for some reasons the Use statement for Collection class was missing in my file. Make sure you have these two lines:

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

Upvotes: 0

Fr&#233;d&#233;ric
Fr&#233;d&#233;ric

Reputation: 529

private ArrayCollection $posts;

is a direct dependence to Doctrine :

use Doctrine\Common\Collections\ArrayCollection;

If you desagree, perhaps because it breaks the SOLID "D", try to use the pure php pseudo type Iterable (https://www.php.net/manual/en/language.types.iterable.php), like this:

private iterable $posts;

Upvotes: 1

Kunwara
Kunwara

Reputation: 581

After some digging a found the answer changing the ArrayCollection to Collection fixed my issue

change:

/**
 * @ORM\OneToMany(targetEntity=Post::class, mappedBy="Category_id")
 */
private \Doctrine\Common\Collections\ArrayCollection $posts;

to:

/**
 * @ORM\OneToMany(targetEntity=Post::class, mappedBy="Category_id")
 */
private \Doctrine\Common\Collections\Collection $posts;

Upvotes: 40

Djamel KHIREDDINE
Djamel KHIREDDINE

Reputation: 211

The problem is in th type hinting (ArrayCollection => Collection)

change:

/**
 * @ORM\OneToMany(targetEntity=Post::class, mappedBy="Category_id")
 */
private ArrayCollection $Posts;

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

by:

/**
 * @ORM\OneToMany(targetEntity=Post::class, mappedBy="Category_id")
 */
private Collection $Posts;

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

Upvotes: 10

prieber
prieber

Reputation: 574

$this->$posts[] = $posts;

Looks like this line should be:

$this->$posts[] = $post;

Upvotes: 2

Related Questions