Nick
Nick

Reputation: 1269

Doctrine Event Listener for adding/removing Many to Many relations

I make heavy use of Entity Listeners for logging purposes, generally works really well and keeps all the code out of the controllers/services.

One thing I haven't been able to achieve is logging of items added to a ManyToMany relation. In this instance I want to log when a size is added/removed from a product

/**
 * @ORM\Entity
 * @ORM\EntityListeners({"EventListener\ProductListener"})
 * @ORM\Table(name="products")
 */
class Product
{
    // ...

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Size")
     * @ORM\JoinTable(name="productSizes",
     *      joinColumns={@ORM\JoinColumn(name="productId", referencedColumnName="productId")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="sizeId", referencedColumnName="sizeId")}
     * )
     */
    protected $sizes;

    /**
     * @param Size $size
     * @return Product
     */
    public function addSize(Size $size)
    {
        $this->sizes[] = $size;
        return $this;
    }

    /**
     * @param Size $size
     */
    public function removeSize(Size $size)
    {
        $this->sizes->removeElement($size);
    }

    /**
     * @return ArrayCollection
     */
    public function getSizes()
    {
        return $this->sizes;
    }

    // ...
}

Then inside the entity listener

class ProductListener
{
    // ...

    /**
     * @ORM\PostPersist
     */
    public function postPersistHandler(Product $product, LifecycleEventArgs $args)
    {
        $this->getLogger()->info("Created product {$product->getSku()}", [
            'productId' => $product->getId()
        ]);
    }

    /**
     * @ORM\PostUpdate
     */
    public function postUpdateHandler(Product $product, LifecycleEventArgs $args)
    {
        $context = $args->getEntityManager()->getUnitOfWork()->getEntityChangeSet($product);

        $context['productId'] = $product->getId();
        $this->getLogger()->info("Updated product", $context);
    }

    // ...
}

So how can I get the colours added/removed from the unit of work? I'm assuming this is available somewhere but I can't find it.

Upvotes: 0

Views: 2112

Answers (1)

Paulius Jarmalavicius
Paulius Jarmalavicius

Reputation: 126

In your ProductListener

 $product->getSizes() returns instance of Doctrine\ORMPersistentCollection. Then you can call 2 methods:

 - getDeleteDiff - returns removed items
 - getInsertDiff - returns added items

Upvotes: 11

Related Questions