-->

Get old data in preUpdate Sonata Admin Bundle

2019-02-12 17:47发布

问题:

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?

回答1:

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



回答2:

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.