aemslingjcrsling-models

Get foundation component property in parent node sling model


I just start using Sling models, and I have an issue to retrieve a child node property in the parent model. Here is my JCR structure

the image node is a from the foundation components. and my aim is to get the "filerefernce" property of the image component in the Topbanner node then in its sightly script. here is my topbanner node model :

@Model(adaptables=Resource.class)
public class TopBanner {



 @Self @Via("resource")
 private Resource bannerBackGroundImage;

 private String bannerBgImagePath;

 // @Inject 
 // private String bannerTitle;

 // @Inject 
 // private String bannerDescription;
 // 
 // @Inject 
 // private String bannerButtonText;
 // 
 // @Inject 
 // private String bannerButtonLink;

  @SlingObject
  private ResourceResolver resourceResolver;

  @PostConstruct
  public void init() {
    TopBanner.LOG.info("we are here");

    try {
bannerBackGroundImage=resourceResolver.getResource("/apps/ads/components/structure/TopBanner2/Image");
        this.bannerBgImagePath=bannerBackGroundImage.adaptTo(ValueMap.class).get("fileReference",String.class);
    } catch(SlingException e) {
        TopBanner.LOG.info("Error message  **** " + e.getMessage());
    }   

}
// getters omitted 

the error I am getting is Identifier Mypackage.models.TopBanner cannot be correctly instantiated by the Use API


Solution

  • If your target is to get 'fileReference' try this:

    @Self
    private SlingHttpServletRequest request;
    
    @ValueMapValue(name = DownloadResource.PN_REFERENCE, injectionStrategy = InjectionStrategy.OPTIONAL)
    private String fileReference;
    

    then to get our asset use following:

    if (StringUtils.isNotEmpty(fileReference)) {
            // the image is coming from DAM
            final Resource assetResource = request.getResourceResolver().getResource(fileReference);
            if (assetResource != null) {
                Asset asset = assetResource.adaptTo(Asset.class);
                //Work with your asset there.
            }
        }
    

    also add to your class annotation:

    @Model(adaptables = { SlingHttpServletRequest.class })