Created

Mar 26, 2013

Changing resources in AEM5.6

Posted by Feike Visser

In this blogpost I want to show you some code around a new way you can change resources via the ResourceResolver

In the new ResourceResolver there are methods available to create/update/delete your Resources.

This is now quite a straightforward way, I will demonstrate this via some basic code samples.

Changing a resource

Here a code sample how to add / change a property on an existing resource. Via the ModifiableValueMap you can modify the properties.

ResourceResolver resourceResolver = getResourceResolver();
Resource resource = getSlingRequest().getResource();
		
ModifiableValueMap mvp = resource.adaptTo(ModifiableValueMap.class);

// adding and changing a property
if ( mvp.containsKey("test")) {
	String propValue = mvp.get("test", String.class);
	mvp.put("test", propValue + "1");
} else {
	mvp.put("test", "test");
}

Create / Delete a resource

Via the methods create() / delete() you can create and delete a new resource.

ResourceResolver resourceResolver = getResourceResolver();
Resource resource = getSlingRequest().getResource();

// adding and removing a child node
if ( resource.getChild("person") == null ) {
	Map props = new HashMap();
	props.put("firstname", "feike");
	props.put("lastname", "visser");
			
	Resource newResource = resourceResolver.create(resource, "person", props);
} else {
	resourceResolver.delete(resource.getChild("person"));
}

Saving / Reverting changes

Via the methods .commit() and .revert() you can either save or rollback the changes.

if ( resourceResolver.hasChanges() ) { 
	resourceResolver.commit();
}