Get old data in preUpdate Sonata Admin Bundle

tttony picture tttony · Apr 19, 2013 · Viewed 7.5k times · Source

I have a product entity and it has an images field that store the images names from the product but the images names depends of a part_number field that is unique, so if the user make a mistake in the part number and he wants to edit it then I also have to change the images names

I tried this but it does not works:

// class ProductsAdmin extends Admin

public function preUpdate($product) {

    $old_product = $this->getSubject();

    if ($old_product->getPartNumber() != $product->getPartNumber)
    {
         // change file names
    }

    $this->saveFile($product);
}

How I get the original row in preUpdate() function?

Answer

Błażej Kocik picture Błażej Kocik · Jan 19, 2014

According to the topic taken from the official SonataAdmin google forum: https://groups.google.com/forum/#!topic/sonata-devs/0zML6N13i3U you need to make use of the class UnitOfWork: http://www.doctrine-project.org/api/orm/2.3/class-Doctrine.ORM.UnitOfWork.html

Do this way:

public function preUpdate($object)
{
    $em = $this->getModelManager()->getEntityManager($this->getClass());
    $original = $em->getUnitOfWork()->getOriginalDocumentData($object);
}

Thus you get an array of values of your database entity. E.g: to get access to the value password of your entity do:

$password = $original['password'];

That's all. Enjoy :)