Expand my Community achievements bar.

SOLVED

How to access Sling Model in JAVA class that extends WCMUse/WCMUsePojo

Avatar

Level 7

Hi Team,

Is it possible to get the Sling model in the class that extends WCMUse/WCMUsePojo? I tried the below code in Sightly class but I'm getting null-

MySlingModel mySlingModel = getResource().adaptTo(MySlingModel.class);

if (null != mySlingModel ) {        

    LOG.info("mySlingModel IS NOT NULL");

} else {

    LOG.info("mySlingModel IS NULL:");

}

I tried the below scenarios also but I'm getting NULL -

  • MySlingModel mySlingModel = getRequest().getResourceResolver().getResource(getResource().getPath()).adaptTo(MySlingModel.class);
  • MySlingModel mySlingModel = getRequest().adaptTo(MySlingModel.class);

Is it good practice do use Sling Models in sightly class?

Thanks,

AryA.

1 Accepted Solution

Avatar

Correct answer by
Level 10

We have a community article that shows use of Sightly and Sling Models -- see: 

https://helpx.adobe.com/experience-manager/using/domparser.html

Hope this helps... 

View solution in original post

4 Replies

Avatar

Correct answer by
Level 10

We have a community article that shows use of Sightly and Sling Models -- see: 

https://helpx.adobe.com/experience-manager/using/domparser.html

Hope this helps... 

Avatar

Level 5

I think you can adapt straight from SlingHttpServletRequest for this particular use case.

@Model(adaptables={SlingHttpServletRequest.class}) public class MyModel{ ... }

And to be honest, once you do that, (aside from the helper functions) I'm not sure there's a real advantage in even extending the WCMUsePojo, since this gives you all the same functionality. (FWIW: I've moved all mine away from extending and just using the model adaption method)

I wrote a little opinionated demo on my site: http://scrupulo.com/blog/making-more-adaptable-sling-models-in-aem6

Avatar

Level 7

Yes Scott. I have gone through that but the class Parser which is mentioned in the article is not extending the WCMUse/WCMUsePojo. It is directly accessed in component's sightly html.

But I would like to access it in the class that extends WCMUse/WCMUsePojo.

Please suggest. 

Thanks.

Avatar

Level 10

When using Sling Models in Sightly - this is the way you do it. That is why the article was written - i will update Model article to state that. 

As B Stockwell points out - there is no advantage of using WCMUse when using Sling Models.