May 1, 2020
Estimated Post Reading Time ~

Retrieve Composite Multifield child values in AEM through Java (WCMUsePojo)

In this post, we'll use the Java WCMUsePojo API to retrieve the multifield child values in our sightly code.

Since the multifield values stored in the page is stored as child nodes as shown below:



First, we'll create the MultiList bean having the same properties as in our dialog with getters and setters as shown below:

package com.foo.community.core;

public class MultiList {

private String multitext;
private String multinum;
private String multicheck;

public String getMultitext() {
return multitext;
}

public void setMultitext(String multitext) {
this.multitext = multitext;
}

public String getMultinum() {
return multinum;
}

public void setMultinum(String multinum) {
this.multinum = multinum;
}

public String getMulticheck() {
return multicheck;
}

public void setMulticheck(String multicheck) {
this.multicheck = multicheck;
}
}

And then, we'll create a class extending WCMUsePojo where we'll get the current node and then get the products node (where child values of multifield are stored) and iterate over that and set the retrieved property values in List of MultiList bean created above. Below is the implementation of this process:

package com.foo.community.core;

import java.util.ArrayList;
import java.util.List;
import com.adobe.cq.sightly.WCMUsePojo;
import javax.jcr.Node;
import javax.jcr.NodeIterator;

public class MultiListComponent extends WCMUsePojo{

private List multiItems = new ArrayList();

@Override
public void activate() throws Exception {

Node currentNode = getResource().adaptTo(Node.class);
if(currentNode.hasNode("products")){
Node productsNode = currentNode.getNode("products");
NodeIterator ni = productsNode.getNodes();

String multitext;
String multinum;
String multicheck;

while (ni.hasNext()) {

MultiList multiItem = new MultiList();
Node child = (Node)ni.nextNode();

multitext= child.hasProperty("multitext") ?
child.getProperty("multitext").getString(): "";
multinum = child.hasProperty("multinum") ?
child.getProperty("multinum").getString(): "";
multicheck = child.hasProperty("multicheck") ?
child.getProperty("multicheck").getString(): "";

multiItem.setMultitext(multitext);
multiItem.setMultinum(multinum);
multiItem.setMulticheck(multicheck);
multiItems.add(multiItem);
}
}
}

public List getMultiItems() {
return multiItems;
}
}

And use below sightly code (blog.html) to render values in the html:
<div data-sly-use.blog="com.foo.community.core.MultiListComponent">
<h4>Composite Multifield</h4>
<ol data-sly-list.product="${blog.multiItems}">
<li>
${product.multitext} has ${product.multinum} with boolean
${product.multicheck}
</li>
</ol>
</div>


By aem4beginner

No comments:

Post a Comment

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