Note that there are some explanatory texts on larger screens.

plurals
  1. POEmbedded form persistence : get or create
    text
    copied!<p>I work with Symfony2 and doctrine. I currently have an entity called Person. This entity is related to some other entities as a One-To-Many relation (as a Many-To-One unidirectional relation). I want each Person entity to be unique (what I have done in my database by using the UniqueConstraint annotation).</p> <p>To be clear, I will assume that I have two entities called Home and Car which both have a Many-to-One relation to the target entity Person.</p> <p>Then I am using forms to create or edit my entities Car and Home. In these forms, I display a embedded form to create a Person entity or select one existing. I explain : the first field of my embedded form is the name of the person. As the user type the name of the person, a list of the existing persons is displayed (using JQuery Autocomplete UI) and if the user select one of them the other fields are autocompleted.</p> <p>The issue is when the user submit the form with an existing person, I caught an Integrity Error (and I know why, because of my Unique Constraint).</p> <p>One of the first workaround is to add the id field as an hidden input in the embedded form. But then the user can edit the other fields and corrupt the current entity. So no.</p> <p>Another one could be to prevent the persist in the controller if the Person already exist, but as I am using this in many other entities. I will have to duplicate my code, and I do not want to, as the unique constraint is related to the Person entity and not to the Car or Home entity. So no again.</p> <p>The workaround that I am working about is to use a PrePersist Listener waiting for a Person entity, but I do not know how to cancel persist (and maybe it is not possible). I have the following code :</p> <pre><code>public function prePersist(LifecycleEventArgs $args) { $entity = $args-&gt;getEntity(); if($entity instanceof Personne) { $em = $args-&gt;getEntityManager(); $persons = $em-&gt;getRepository('MyBundle:Person')-&gt;findBy(array( // unique fields )); if(count($persons) &gt; 0) { // ... ??? } } </code></pre> <p>I have tried a $em->detach but it is useless as I am already persisting the entity.</p> <p>What I want it is just a kind of a "Get Or Create". I explain, there are only two cases :</p> <ul> <li>the Person entity (not persisted) has all the same fields that one existing in the database (excepted the id field), so the Person entity is the one in the database. I have to "replace" it by the one in the database ;</li> <li>the Person entity (not persisted) is unique in the database, so we create a new one (persist).</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload