Expand my Community achievements bar.

adaptTo returns null in Sling model

Avatar

Level 3

Hi,

 

I am trying to adapt a resource into an Image.class object in my Sling model, but I always get `null` for `image1` even though the resource is correctly returned with all its properties. I tried using `resourceResolver` and `request` below.

 

 

    @Model(
            adaptables = SlingHttpServletRequest.class,
            adapters = {Image.class, ComponentExporter.class},
            resourceType = {TestImageModel.RESOURCE_TYPE},
            defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
    public class TestImageModel extends AbstractComponentImpl implements Image {

         private SlingHttpServletRequest request;
         private ResourceResolver resourceResolver;

        //...

        Image image1 = resourceResolver.getResource("/content/aladin/sean/jcr:content/root/container/testimage/image1").adaptTo(Image.class);

        //...

        Image image1 = request.getResource().getChild("image1").adaptTo(Image.class);

        //...
    }

 

 

I believe the resource path of "/content/aladin/sean/jcr:content/root/container/testimage/image1" should have all the required properties to adapt to Image class, per below.

 

sean12341_0-1697179168267.png

 

What am I missing here to get the actual Image object instead of `null`? I am using AEMaaCS.

 

Thank you,

4 Replies

Avatar

Community Advisor

hello @sean12341 

 

Apologies I am a bit confused.

- The model is already meant for an Image component

- Why in its model are we trying to adapt to Image.class ?

 

If you are trying to extend/customize the functionality of OOTB Image model, then please use Delegation pattern. Example: https://kiransg.com/2021/11/07/aem-core-component-delegation/


Aanchal Sikka

Avatar

Level 3

Hi @aanchal-sikka

 

Sorry I see that my sling model extending from the OOTB Image model can be misleading. Yes I could get the image url path as follow:

 

@Self
@Via(type = ResourceSuperType.class)
private Image img;

//...
img.getSrc()


But in my custom component's cq_dialog, there are actually MULTIPLE images being uploaded via "cq/gui/components/authoring/dialog/fileupload".

 

Those images will require their own Image object to get their respective url, as `img.getSrc()` only returns the url of the extended image.

 

This is why I wanted to adapt the other added images into Image object, so I can call `.getSrc()` on them as well, to making use of the built-in web-optimized image delivery.

 

Hopefully this clarifies,

 

Avatar

Level 3

I found this post here, which indicate that core model classes does not support adaptation from Resource. It was requested to be added but I guess no further action taken.