symfonysymfony4sonatasonata-media-bundle

Sonata Media Bundle - How to get Image or Gallery by Id


Is it possible to get an image or gallery from Sonata Media Bundle by Id?

I know how to get an image or gallery which is related to an entity. But in this case I just want to get an image or gallery without an entity.

Something like:

$media = $mediaProvider->getMediaById(12);

or

$gallery = $mediaProvider->getGalleryById(2);

Does anyone know how to do this?


Solution

  • I found a solution!

    In the controller get the gallery:

    $galleryId = 3;
    $repo = $this->getDoctrine()->getRepository('ApplicationSonataMediaBundle:Gallery');
    $gallery = $repo->find($galleryId);
    $gallery = $gallery->getGalleryHasMedias();
    

    And in the twig template:

    {% for img in gallery %}
        {% media img.media, 'gallery' %}
    {% endfor %}