Expand my Community achievements bar.

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

Avatar

Administrator

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.



Kautuk Sahni
2 Replies

Avatar

Community Advisor

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

@Via(type = ResourceSuperType.class) ?

 

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

 What are the advantageous in using the above pattern?

 

Avatar

Community Advisor

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