14

I have a Sling Resource object. What is the best way to set or update its property?

Tomek Rękawek
  • 9,204
  • 2
  • 27
  • 43

3 Answers3

36

It depends on the Sling version:

Sling >= 2.3.0 (since CQ 5.6)

Adapt your resource to ModifiableValueMap, use its put method and commit the resource resolver:

ModifiableValueMap map = resource.adaptTo(ModifiableValueMap.class);
map.put("property", "value");
resource.getResourceResolver().commit();

Sling < 2.3.0 (CQ 5.5 and earlier)

Adapt your resource to PersistableValueMap, use its put and save methods:

PersistableValueMap map = resource.adaptTo(PersistableValueMap.class);
map.put("property", "value");
map.save();

JCR API

You may also adapt the resource to Node and use the JCR API to change property. However, it's a good idea to stick to one abstraction layer and in this case we somehow break the Resource abstraction provided by Sling.

Node node = resource.adaptTo(Node.class);
node.setProperty("property", "value");
node.getSession().save();
Markus
  • 452
  • 3
  • 12
Tomek Rękawek
  • 9,204
  • 2
  • 27
  • 43
  • How to specify the type of value? map.put("property", "value") sets the type as String. How to customize the type while using put() method! – Jezwin Varghese Nov 30 '19 at 19:17
4

As many developers are not fond of using Node API. You can also use ValueMap and ModifiableValueMap APIs to read and update property respectively.

Read Value through ValueMap

ValueMap valueMap = resource.getValueMap();
valueMap.get("yourProperty", String.class);

Write/Modify property through ModifiableValueMap

ModifiableValueMap modifiableValueMap = resource.adaptTo(ModifiableValueMap.class);
modifiableValueMap.put("NewProperty", "Your Value");  //write
modifiableValueMap.put("OldProperty", "Updated Value"); // Modify

After writing property to a node, save these values by committing the 'resourceResolver'

You'll need system/service user for admin resourceResolver.

Go through this documentation for more info about service user.

Community
  • 1
  • 1
Manisha Bano
  • 1,853
  • 2
  • 22
  • 34
1

It is not working in publish. But if user logged-In as admin it will work.

ModifiableValueMap map = resource.adaptTo(ModifiableValueMap.class);
map.put("property", "value");
resource.getResourceResolver().commit();
MarmiK
  • 5,639
  • 6
  • 40
  • 49
vasi
  • 11
  • 1