April 24, 2020
Estimated Post Reading Time ~

Update a node property using an AEM bundle

In the previous session, we have seen how to obtain a Resource. We later translated the Resource into a Page object, and then programmatically obtained its title. We will see one more example. Here, using an AEM bundle, we will write a property to the Page we created. In this case, too, we need to use a Resource object to obtain a Session object using which we can save what we write.

Let us start:

1. Create a new interface: SearchService.java.
(There is a reason for using this name. In the next session, we are going to discuss searching.)
2. Add the following method.
public void addProperty();.
3. Create the implementation class: SearchServiceImpl.java
4. Implement the addProperty() method.
5. Get the ResourceResolver.
(Visit the previous post to see what the code accomplishes.)
6. Map<String, Object> param = new HashMap<String, Object>();
7. param.put(ResourceResolverFactory.SUBSERVICE, "readService");
8. ResourceResolver resourceResolver=null;
resourceResolver = resolverFactory.getServiceResourceResolver(param);
9. Obtain the resource.
Resource pageResource = resourceResolver.getResource("/content/aem-company/jcr:content");
Note that we need to add the property to the jcr:content node of the page we created.
10. Translate the resource into a node using the adaptTo() class.
Node myNode = pageResource.adaptTo(Node.class);
11. Set a property to the node.
myNode.setProperty("author", "sunil");
12. Obtain the session from resourceResolver.
Session session = resourceResolver.adaptTo(Session.class);
13. Save the session:
session.save();
14. Deploy the bundle.
15. Add a method in the bundleservice component.
16. <%
17. com.aemcompany.myproject.SearchService searchService=sling.getService(com.aemcompany.myproject.SearchService.class);
18. searchService.addProperty();
%>
19. Access the page so that the method is called.
20. Log into CRXDELite.
21. See the page properties and ensure that the new property is added.
That’s it. See you soon.



By aem4beginner

1 comment:

  1. I tried to follow the same , but i did not get the exact output

    ReplyDelete

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