3

I have a very basic symfony 5 + easyadmin 3 app. I created using the make:entity two entities: Posts and Categories

When I try to edit Category to assign Posts, posts are not saved in DB. But If I add the category on the post edit is saves in db.

Any idea what I'm missing here?

CategoryCrudController.php

public function configureFields(string $pageName): iterable
{
    if (Crud::PAGE_EDIT === $pageName)
    {
        yield TextField::new('title');
        
        yield DateTimeField::new('created_at')
            ->setFormTypeOption('disabled','disabled');
       
        yield AssociationField::new('posts')
            ->autocomplete();

Entity Category.php

/**
 * @ORM\OneToMany(targetEntity=Post::class, mappedBy="category")
 */
private $posts;

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


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

public function addPost(Post $post): self
{
    if (!$this->posts->contains($post)) {
        $this->posts[] = $post;
        $post->setCategory($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->getCategory() === $this) {
            $post->setCategory(null);
        }
    }

    return $this;
}
Cedric
  • 181
  • 1
  • 8
  • You’re right by it was just just a copy/paste mistake because I edited the names from my code to make it more understandable. I really appreciate you taking the time to answer anyway. I edited my question. – Cedric Mar 21 '21 at 01:58
  • I think this answer on another issue is related. https://stackoverflow.com/a/35765987/7891743 I created, using make:entity a relation field in plural and I’m think it’s the issue here. Used “posts” ManyToOne Category – Cedric Mar 21 '21 at 02:01

1 Answers1

15

Found the solution thanks to: https://github.com/EasyCorp/EasyAdminBundle/issues/860#issuecomment-192605475

For Easy Admin 3 you just need to add

->setFormTypeOptions([
    'by_reference' => false,
])

CategoryCrudController.php

public function configureFields(string $pageName): iterable
    {
        if (Crud::PAGE_EDIT === $pageName)
        {
            yield TextField::new('title');

            yield DateTimeField::new('created_at')
                ->setFormTypeOption('disabled','disabled');

            yield AssociationField::new('posts')
                ->setFormTypeOptions([
                    'by_reference' => false,
                ])
                ->autocomplete();
Cedric
  • 181
  • 1
  • 8