Symfony2 / Doctrine 2 : Sluggable extension : Access slug value during onFlush or postUpdate Event

291 Views Asked by At

I have a Restaurant entity with a One-To-One relationship with an ImageRestaurant entity.

I can edit both entities using a single form (ImageRestauranType is embedded in RestaurantType).

Restaurant entity has a slug, which is generated thanks to the StofDoctrineExtensionsBundle, and using the Gedmo\Sluggable annotation.

I am trying to rename the file linked to my ImageRestaurant entity using the slug attribute (slug.jpg for example) each time a Restaurant entity is updated and the slug attribute is regenerated. I want also to change the name attribute of the ImageRestaurant entity.

I have two options using the Doctrine events :

  1. onFlush event :

I have access to the entities scheduled for update (Restaurant) but at this time, the updated slug is not accessible. So I can not update the file and the ImageRestaurant entity.

  1. postUpdate event :

I have access to the updated slug but as described in the documentation this event is not relevant to persistence in database :

The three post events are called inside EntityManager#flush(). Changes in here are not relevant to the persistence in the database, but you can use these events to alter non-persistable items, like non-mapped fields, logging or even associated classes that are not directly mapped by Doctrine.

For this event, as I have access to the entities ID I thought I could fetch both entities Restaurant (the frehsly updated one) and ImageRestaurant from database and proceed to file and ImageRestaurant update ?

Any ideas on how I could achieve this ?

1

There are 1 best solutions below

0
On BEST ANSWER

The solution is quite simple. The slug is generated for the doctrine event onFlush. My listener (subscriber in my case) needs to be executed later than the Sluggable listener to have access to the regenerated slug attribute.

Here is how I registered my subscriber (note the difference between Symfony listeners and doctrine listeners - have a look at Stof comment) :

fbn_guide.doctrine_listener:
    class : FBN\GuideBundle\EventListener\DoctrineListener
    arguments: [@fbn_guide.image_manager]
    tags:
        - { name: doctrine.event_subscriber, connection: default, priority: -10000 }