@koddrive

Как исправить ошибку «Maybe you forget to persist it in the entity manager?» во время работы формы entityType?

Не нашел решение ошибки "Entity of type "App\Entity\Books" passed to the choice field must be managed. Maybe you forget to persist it in the entity manager?"
Есть сущность books
namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\BooksRepository")
 */
class Books
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Users", mappedBy="books")
     * @ORM\JoinColumn(name="books", referencedColumnName="id")
     */
    private $users;

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

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

    /**
     * @return Collection|Users[]
     */
    public function getUsers(): Collection
    {
        return $this->users;
    }

    public function addUser(?Users $user): self
    {
        if (!$this->users->contains($user))
        {
            $this->users[] = $user;
            $user->addBook($this);
        }

        return $this;
    }

    public function removeUser(?Users $user): self
    {
        if ($this->users->contains($user))
        {
            $this->users->removeElement($user);
            $user->removeBook($this);
        }

        return $this;
    }

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

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

        return $this;
    }


}


Есть сущность users:
namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UsersRepository")
 */
class Users
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Books", inversedBy="users")
     *  @ORM\JoinColumn(name="users", referencedColumnName="id")
     */
    private $books;

    public function __construct()
    {
        $this->books = 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|Books[]
     */
    public function getBooks(): Collection
    {
        return $this->books;
    }

    public function addBook(?Books $book): self
    {
        if (!$this->books->contains($book)) {
            $this->books[] = $book;
           // $book->addUser($this);
        }

        return $this;
    }

    public function removeBook(?Books $book): self
    {
        if ($this->books->contains($book)) {
            $this->books->removeElement($book);
         //   $book->removeUser($this);
        }

        return $this;
    }
}

Между ними связь ManyToMany.
Я хотел через форму EntityType сделать возможность выбирать сразу несколько книг при регистрации пользователя
namespace App\Form;

use App\Entity\Books;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;

class UserType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('name', TextType::class, [
                'label' => 'Имя',
                'required'   => false,
                'attr' => ['placeholder' => 'Введите имя']
            ])
            ->add('books', EntityType::class, array(
                'class' => Books::class,
                'choice_label' => 'name',
                'label' => 'Книги',
                'multiple' => true
            ))
            ->add('save', SubmitType::class, [
                'label' => 'Отправить'
            ]);
    }

}

Но встречаю ошибку "Entity of type "App\Entity\Books" passed to the choice field must be managed. Maybe you forget to persist it in the entity manager?" и не знаю как ее решить. Кто знает как решить эту ошибку, или кто знает как привязать ManyToMany к entityType?
  • Вопрос задан
  • 806 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы