12

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?

tttony
  • 4,944
  • 4
  • 26
  • 41

2 Answers2

22

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 :)

Błażej Kocik
  • 1,689
  • 1
  • 17
  • 20
  • 21
    Remember that for mongoDB you will use 'getOriginalDocumentData' as a method on the unitOfWork but for mysql you will need to use 'getOriginalEntityData'. – Geert Wille Feb 05 '14 at 22:32
0

If you just do a doctrine query in the preUpdate function to get the product from the database you'll have the old object. Then do the comparison and you're good to go.

Geert Wille
  • 1,656
  • 13
  • 18
  • Doctrine creators do not recommend use getUnitOfWork() as far as I remember. So this solution should be better – Darius.V Dec 19 '18 at 13:26