adaptTo returns null in Sling model | Adobe Higher Education
Skip to main content
Level 3
October 13, 2023

adaptTo returns null in Sling model

  • October 13, 2023
  • 3 の返信
  • 1490 ビュー

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.

 

 

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

 

Thank you,

このトピックへの返信は締め切られました。

3 の返信

aanchal-sikka
Community Advisor
Community Advisor
October 13, 2023

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
sean12341作成者
Level 3
October 13, 2023

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,

 

sean12341作成者
Level 3
October 23, 2023

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.