Search code examples
symfonydoctrinevichuploaderbundle

VichUploaderBundle: How to get related entity ID in DirectoryNamer?


I am configuring a directory namer included in VichUploaderBundle to upload multiple files.

I have two entities Soundtrack and Song. The collection of Songs are processed in my controller like this:

//...
if ($form->isValid()) {
   $soundtrack->setSlug("sw-ep-vii");
   $soundtrack->setName("Star Wars Episode VII");
   foreach ($soundtrack->getSongs() as $song) {
      $em->persist($song);
   }
   $em->persist($soundtrack);
   $em->flush();
}

When persisting $soundtrack VichUploaderBundle uploads the Song files and moves them to the directory defined in config.yml or to a dynamic route defined in a service called DirectoryNamer, which is the one i'm interested.

In my SoundtrackDirectoryNamer, the persisting Song entity is automagically passed to the directoryName() method so i want to just return the associated Soundtrack.id as a directory name like:

class SoundtrackDirectoryNamer implements DirectoryNamerInterface
{
    public function directoryName($song, PropertyMapping $mapping)
    {   
        return $song->getSoundtrack()->getId();                                                                                    
    }
}

Now the problem is Soundtrack is still not persisted to the database so it has no auto-incremented id yet.

If I change $song->getSoundtrack()->getId() to $song->getSoundtrack()->getSlug(), it creates the directory sw-ep-vii correctly and everything works fine - as i previously set the slug in the controller with $soundtrack->setSlug("sw-ep-vii").

Any workaround for this?


Solution

  • I'm the current maintainer of the bundle.

    That's a known issue (to be exact, it's more a won't fix).

    The directory and file name are computed before the entity is actually saved, so for new objects the identifier is unavailable. By design, there is nothing that can be done to avoid this… except if you don't use auto-incremented identifiers but generated ones (UUIDs or slugs for instance).