0

I have a little problem with the PreUpdate LifecycleCallbacks in Symfony.

I have an entity User with a OneToMany relation with an entity product.

class User{
     /**
     * @ORM\OneToMany(targetEntity="Product", mappedBy="formulario", cascade={"persist", "remove"})
     */
    private $products;
}

class Product{
     /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="products")
     * @ORM\JoinColumn(name="user", referencedColumnName="id")
     */
    private $user;
}

My problem is when I add or remove a product from the User. When this hapends I want to launch a PreUpdate function to make some changes in the User Entity. But the PreUpdate is not fire when changing the entity Product from the User.

Thanks a lot!!!

Angel
  • 1,970
  • 4
  • 21
  • 30
  • 1
    $produt on entity User is the inverse side of the association, I'm not sure any lifecycle callback will be called on User when Product (the owning side) is modified. You may try to put the callback on Product entity – Florent Jul 23 '13 at 12:49
  • Ok! That works! Thanks! But, is there any way to put the PreUpdate in the User Entity? In some way, the User is changing adding a product... For me is too much easier and organized to see the function in the User entity. In your way I have to call the function of the User from the PreUpdate Product Entity { $this->getUser()->PreUpdateUser() }. So I have to have two functions, the PreUpdate for the User, and the PreUpdate for the Product (which calls the PreUpdate User) Any way, Thanks a lot! – Angel Jul 23 '13 at 13:50
  • Also, the PreRemove event is fired too, but it doesn't make changes. So if I remove a Product, the PreRemove function is fired, but the code $this->getUser()->setSomeField() doesn't make effect, so the Product is deleted from the DB but the User doesn't change :( It is because I delete the Product object, so the changes in FK of the user get lost? – Angel Jul 23 '13 at 14:19
  • You should have a look at http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html, §5.1 about owning and inverse side. If you change something on the inverse side, it won't have any effect on Doctrine. You can bypass that by modifying both entities on owning and inverse side setter methods. For the lifecycle callback I see no other solution though. – Florent Jul 23 '13 at 14:29

2 Answers2

2

Changing related entities is not allowed using a preUpdate listener.

Changes to associations of the updated entity are never allowed in this event, since Doctrine cannot guarantee to correctly handle referential integrity at this point of the flush operation.

... from the documentation.

Nicolai Fröhlich
  • 51,330
  • 11
  • 126
  • 130
0

I have got same issue and I have solved it by update $user in preUpdate() then schedule an extra update:

    $args->getEntityManager()->getUnitOfWork()->scheduleExtraUpdate($user, array(
        'field_name' => array($oldValue, $newValue)
    ));