Expand my Community achievements bar.

SOLVED

How to add cq:styleids manually and via code in Java

Avatar

Level 7

Ronnie09_0-1635266937332.png

Ronnie09_1-1635267021229.png

I am trying to add these things manually and via code both way I can't do it 

Can you please help with code and manual progress both

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @Ronnie09 

 

1. JCR API
You may  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();


2. Read Value through ValueMap

You can also use ValueMap and ModifiableValueMap APIs to read and update property respectively.

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.

Regards,

Santosh

View solution in original post

1 Reply

Avatar

Correct answer by
Community Advisor

Hi @Ronnie09 

 

1. JCR API
You may  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();


2. Read Value through ValueMap

You can also use ValueMap and ModifiableValueMap APIs to read and update property respectively.

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.

Regards,

Santosh