September 19, 2020
Estimated Post Reading Time ~

How to create a node or drop component in AEM using java program?

A simple and easy java code to create/add a node or drop a component in AEM.

In this tutorial, we are dropping an AEM component on the AEM page (in a parsys or under a specific node) programmatically. To complete this requirement, we have to write code as follows:

First, we have to create an object of ResourceResolver either using ResourceResolverFactory or using a session. In this example, we use ResourceResolverFactory interface service API to create the object of ResourceResolver to get the resource from AEM. (code snippet line # 6)

Now we will get the resource using ResourceResolver and adapt that resource in a JCR Node type, so we can deal with that resource and perform manipulation. ResourceResolver has a method getResource resource which makes AME resource available for manipulation. getResource() method required a relative to as a parameter to get that resource. (code snippet line # 7)

Then using JCR API we will add a node under that resource/Node with its name(component name) and type(component type). (code snippet line # 8)

After that, we will set all the required property for that component. (code snippet line # 9-13)

Below is the complete code to drop a component in AEM using java. If you have any doubt please comment on your doubt and questions in the comment section.

@Reference

private ResourceResolverFactory resolverFactory;

ResourceResolver resolver;

private void addNodeOrComponentInAEM() {

 try {

  resolver = resolverFactory.getServiceResourceResolver(null);

  Node jcrContent=resolver.getResource("/content/we-retail/ca/en/men/jcr:content").adaptTo(Node.class);

  Node nextbuttonNode=jcrContent.addNode("nextButton","nt:unstructured");

  nextbuttonNode.setProperty("buttonType", "submit");

  nextbuttonNode.setProperty("componentName", "coralButton");

  nextbuttonNode.setProperty("fieldId", "submit");

  nextbuttonNode.setProperty("fieldLabel", "Next");

  nextbuttonNode.setProperty("sling:resourceType", "granite/ui/components/coral/foundation/button");

 } catch (Exception e) {

 } 

}



By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.