Sling model – Retrieving properties of child resources | AEM Community Blog Seeding | Community
Skip to main content
kautuk_sahni
Community Manager
Community Manager
September 7, 2021

Sling model – Retrieving properties of child resources | AEM Community Blog Seeding

  • September 7, 2021
  • 2 replies
  • 4346 views

BlogImage.jpg

Sling model – Retrieving properties of child resources by Kiran

Abstract

In AEM, we fetch the values of multiple properties via java code and display them in HTL.

Common Way of fetching the properties:

Resource resource = resourceResolver.getResource(request.getParameter("resourcePath"));
//Adapting the resource to a node
resource.adaptTo(Node.class).getProperties();
//Adapting the resource to an asset
resource.adaptTo(Asset.class).getMetadata();
//Adapting the resource to valuemap
resource.adaptTo(ValueMap.class).get("propertyName", String.class);
There are many other adapters available that we can adapt a resource with. You can check them here.

Fetching the property values of a sub-resources becomes complex here. So, lets discuss a simpler way to resolve this problem.

Create a new sling model:

Let’s create a new model with the properties that we need from the child nodes. In the below example, the resource is an asset.

@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class ChildResourceModel {

@Inject
@Named("jcr:content/metadata/dc:title")
private String title;

@Inject
@Named("jcr:content/metadata/dc:description")
private String description;

@Inject
@Named("jcr:content/cq:name")
private String name;

public String getTitle() {
return title;
}

public String getDescription() {
return description;
}

public String getName() {
return name;
}

}

Read Full Blog

Sling model – Retrieving properties of child resources

Q&A

Please use this thread to ask the related questions.

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.

2 replies

Anny0505
Community Advisor
Community Advisor
September 7, 2021

If we can create a model for child resource and adapt it in the main model class then what is the use of 

@2434638(type = ResourceSuperType.class) ?

 

We have in built ResourceSuperType.class and annotation @2434638.

 What are the advantageous in using the above pattern?

 

Manu_Mathew_
Community Advisor
Community Advisor
September 19, 2021

Very nice way of using @Named annotation

Advantages of this approach:

  1. Can re-use the model
  2. Less code
  3. Can enhance it to add multiple properties
  4. Can be iterated over multiple resources