Question

I want to make a single revision option for saving certain objects in Sonata Admin.

I though to do this in the following way:

  • user edits entry
  • form is validated
  • the new information is saved as a separate entry (i'll call it revision)
  • the original object is not modified, except for a relation to the revision

So the code looks something like this (source Sonata\AdminBundle\Controller\CRUDController::editAction()):

$object = $this->admin->getObject($id);
$this->admin->setSubject($object);
$form = $this->admin->getForm();
$form->setData($object);

$form->bind($this->get('request')); // does this persist the object ?

// and here is what I basically want to do:
$object->setId(null);
$orig = $em->getRepository("MedtravelClinicBundle:Clinic")->find($id);
$orig->setRevision($object);
$this->admin->update($orig);

The problem is that $orig loads the already modified, so var_dump($orig === $object) is true.

I also tried $em->getUnitOfWork()->getOriginalEntityData($object); - which grabs the correct data, but as an array, not as an object (this will probably be the last resort).

So, how can I get (and save) the original object after the form bind took place ?

Was it helpful?

Solution

I think you should use the clone keyword to get a independent instance of the object you want to store. It should works by following these steps:

  1. Load the original entity ($object)
  2. Clone the original entity to get a new temporary entity ($newObject)
  3. Alter the $newObject to make it a new entry: $newObject->setId(null);
  4. Bind $newObject to the form
  5. Save (persist) $newObject as a revision
  6. Add the revision to ($object) and persist it too

I hope that if the form is invalid you won't lose all the data sent by the user.

Just in case, I used this answer to find the differences between the original entity and the one modified by the form.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top