symfony - Embedded form persistence : get or create -


i work symfony2 , doctrine. have entity called person. entity related other entities one-to-many relation (as many-to-one unidirectional relation). want each person entity unique (what have done in database using uniqueconstraint annotation).

to clear, assume have 2 entities called home , car both have many-to-one relation target entity person.

then using forms create or edit entities car , home. in these forms, display embedded form create person entity or select 1 existing. explain : first field of embedded form name of person. user type name of person, list of existing persons displayed (using jquery autocomplete ui) , if user select 1 of them other fields autocompleted.

the issue when user submit form existing person, caught integrity error (and know why, because of unique constraint).

one of first workaround add id field hidden input in embedded form. user can edit other fields , corrupt current entity. no.

another 1 prevent persist in controller if person exist, using in many other entities. have duplicate code, , not want to, unique constraint related person entity , not car or home entity. no again.

the workaround working use prepersist listener waiting person entity, not know how cancel persist (and maybe not possible). have following code :

public function prepersist(lifecycleeventargs $args) {    $entity = $args->getentity();    if($entity instanceof personne) {      $em = $args->getentitymanager();     $persons = $em->getrepository('mybundle:person')->findby(array(       // unique fields               ));      if(count($persons) > 0) {       // ... ???     }  } 

i have tried $em->detach useless persisting entity.

what want kind of "get or create". explain, there 2 cases :

  • the person entity (not persisted) has same fields 1 existing in database (excepted id field), person entity 1 in database. have "replace" 1 in database ;
  • the person entity (not persisted) unique in database, create new 1 (persist).

create own getorcreate() method , call inside listener. see post symfony2 doctrine findoneorcreate

another possibility data transformers. http://symfony.com/doc/current/cookbook/form/data_transformers.html


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -