0

When an entity is saved in my app, I want to add its slug field to a lookup table. To make this as least intrusive as possible, I wrote up an event subscriber. According to this post, I cannot INSERT on postUpdate events, so I tried postFlush:

class SlugsSubscriber implements EventSubscriber {
    public function getSubscribedEvents() {
        return array('postFlush');
    }

    public function postFlush(PostFlushEventArgs $args) {
        $em = $args->getEntityManager();
        $needsFlush = false;

        error_log("postFlush");

        foreach ($em->getUnitOfWork()->getScheduledEntityInsertions() as $entity) {
            // To prevent short-circuit
            $tmp = $this->registerSlugs($entity, $entityManager);
            if($tmp) $needsFlush = true;
        }

        foreach ($em->getUnitOfWork()->getScheduledEntityUpdates() as $entity) {
            // To prevent short-circuit
            $tmp = $this->registerSlugs($entity, $entityManager);
            if($tmp) $needsFlush = true;
        }

        if($needsFlush) {
            error_log("Flushing");
            $em->flush();
        }
    }

    protected function registerSlugs($entity, EntityManager $entityManager) {
                    error_log("register slugs");
        if($entity instanceof Product) {
            $this->registerProductSlugs($entity, $entityManager);
                            return true;
        } elseif($entity instanceof Category) {
            $this->registerCategorySlugs($entity, $entityManager);
                            return true;
        }
                    return false;
    }
}

However, when I try to save an entity now, the method registerSlugs is never called, neither on an update nor a new insertions.

Where did I go wrong?

Community
  • 1
  • 1
Lanbo
  • 15,118
  • 16
  • 70
  • 147

1 Answers1

0

You need to get a database object, edit it, persist it, then flush it so that it's saved back to the database. You cannot call flush without first persisting some object which is why registerSlugs is never called. There is nothing to be saved right now.

To change the design, I think you have to have another variable that references an object of the entity you are creating a slug for. This object needs to have a field in the database called slug, you create the slug, then persist the object, then flush so it is saved. Refer to http://symfony.com/doc/current/book/doctrine.html#a-simple-example-a-product for persisting anf flushing an object.

George
  • 1,478
  • 17
  • 28