Doctrine2 - check if the associated entry has been deleted (unidirectional relationship)


Application is build on Symfony2 and Doctrine2.

I'm having unidirectional relationship OneToMany and when the associated entity entry has been deleted the reference column is still set to point to the deleted entry and this is the right behavior because it's just unidirectional association. But this is causing me a problem in a twig template because if I'm going to try to load that it will throw an error entity was not found. I was trying to check in twig using is defined but there was no difference. What would be the best way to check that if the associated entry hasn't been deleted?

Entity example:

class Programme
     * @var string
     * @ORM\ManyToOne(targetEntity="Form")
     * @ORM\JoinColumn(name="form_id", referencedColumnName="id", nullable=true)
     private $form;

Twig check:

{% if programme.form is defined %}
    //always getting here
{% endif %}

If you are using the InnoDB engine for Mysql you can add

onDelete="SET NULL"

To your relationship so when the referenced entity is deleted the field will be set to null.

@ORM\JoinColumn(name="form_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")

This way you dont have links to missing entities at all and it is no longer a twig issue.

If using soft delete:

Then im assuming that you are flagging that entity somehow as deleted and you can do something like:

{% if programme.form.deleted|default(true) != true %}
    //Your form will always be defined but if
    //its deleted then you want to ignore it
{% endif %}

This assumes that you have a deleted column on form. It also uses the default of true for entries that do not have forms.

If you want to simplify this check you can implement a method like isNotDeleted() on your form entity:

public function isNotDelete()
    return $this->deleted === false;

then your twig check would just be:

{% if programme.form.notDeleted|default(false) %}
    //do stuff
{% endif %}

You still need the default filter because if an entity does not have the form association then a method not found exception will be thrown.