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;
}
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();