I am developing twig fiddle, the js/sql/php-fiddle equivalent for Twig language. We can add several templates to render a result, and I have the following entities:
class Fiddle
{
/**
* @var ArrayCollection[FiddleTemplate]
*
* @ORM\OneToMany(targetEntity="FiddleTemplate", mappedBy="fiddle", cascade={"all"}, orphanRemoval=true)
*/
protected $templates;
// ...
}
class FiddleTemplate
{
/**
* @var Fiddle
*
* @ORM\ManyToOne(targetEntity="Fiddle", inversedBy="templates")
* @ORM\JoinColumn(name="fiddle_id", referencedColumnName="id", onDelete="cascade")
* @ORM\Id
*/
protected $fiddle;
/**
* @var string
*
* @ORM\Column(name="filename", type="string", length=64)
* @ORM\Id
*/
protected $filename = 'main.twig';
// ...
}
As you can imagine, I can add / remove templates from UI.
Fiddle's id takes part of the Fiddle entity, so if I want to persist templates for the first time, I first need to persist the fiddle. I do it using a Doctrine event suscriber (see rev history if interested). But if I try to add a template to an already-existing fiddle and save, I come up with the following exception:
Entity of type Fuz\AppBundle\Entity\FiddleTemplate is missing an assigned ID for field 'fiddle'. The identifier generation strategy for this entity requires the ID field to be populated before EntityManager#persist() is called. If you want automatically generated identifiers instead you need to adjust the metadata mapping accordingly.
Sounds logic enough, as I need to spread the Fiddle's instance to the template before persisting.
But I did not found any Doctrine event fired on the Fiddle entity, preUpdate
is not called even if templates
takes part of the entity, because it does not require any update. Only a pre/postPersist
event is fired on the FiddleTemplate entity, but it does not help that much.
I currently do something quite ugly IMHO: before persisting, I call a spreadFiddle
on my entity:
$fiddle->spreadFiddle();
$this->em->persist($fiddle);
$this->em->flush();
The method looks like:
public function spreadFiddle()
{
foreach ($this->templates as $template)
{
$template->setFiddle($this);
}
}
Here my question come:
Is there a better way (using events or annotations) to spread the Fiddle entity to all templates?