Symfony Sonata Admin Bundle: Not saving foreign ID in a OneToMany relationship

If you’re setting up a one-to-many relationship between two entities, don’t forget to set the parent for your child entity as well. Otherwise you’ll end up saving the data without the foreign (parent) id in your database.

In your parent entity class:
public function setChildren($children)
{
  if (count($children) > 0) {
    foreach ($children as $child) {
      $this->addChild($child);
    }
  }

  return $this;
}

public function addChild(Child $child)
{
  $child->setParent($this);
  $this->children->add($child);
}

The „$child->setParent($this);“ part is something that can be easily overseen …

For finally setting the children in the parent entity, you’ll have to add/modify your parent entity listener:
public function prePersist($parent)
{
  $this->preUpdate($parent);
}

public function preUpdate($parent)
{
  $parent->setChildren($parent->getChildren());
}

Original source

Dezember 24th, 2017