javaservletsosgiaemsling-models

How to update the resource property using the valuemap in the Sling servlet?


I’m getting all the pages,taking the jcr:content of all the pages as resource and trying to update the pageTitle property using valueMap by adapting ValueMap to resource, But I’m getting UnsupportedOperationException,

Please can anyone help to sort it out, This is my code snippet:

Resource next = resources.next();
String path=next.getPath();
Resource resource=resourceResolver.getResource(path+"/jcr:content");
ValueMap pages = null;
if (resource != null) {
pages = resource.adaptTo(ValueMap.class);
}
if(pages != null) {
pages.put("pageTitle","MyProject");
}

Solution

  • In your code snippet, I have found that you adapted the ValueMap to the resource.

    Basically, You can’t update any property of the resource directly. In AEM, when you call resource.adaptTo(ValueMap.class) you typically get an immutable ValueMap object that represents the properties of the resource.

    Immutable means that you cannot modify the properties directly using this ValueMap.

    To modify properties, you need to adapt the resource to a ModifiableValueMap, which allows you to make changes to the properties of the resource.

    Here is how you can achieve this,

    ModifiableValueMap modifiableValueMap = resource.adaptTo(ModifiableValueMap.class);
    modifiableValueMap.put("key","value");