May 27, 2020
Estimated Post Reading Time ~

How to read custom Touch UI multifield values in Sightly

Global java implementation for sightly to read TOUCH UI custom multifield values which are stored in Json format

Sample storage of Custom multifield values in repository 
{
 jcr:primaryType: "nt:unstructured",
 products: ["{"productImagePath":"path1","productImgAltText":"altText","cssClass":"test-class"}",
 "{"productImagePath":"productImagePath2","productAltText":"","altText2":"test-class2"}"],
 jcr:createdBy: "admin",
 jcr:lastModifiedBy: "admin",
 jcr:created: "Mon Feb 20 2017 20:36:27 GMT+0530",
 jcr:lastModified: "Thu Mar 02 2017 18:02:01 GMT+0530",
 sling:resourceType: "<component-path>"
}

Create a class multiFieldJsonHelper 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.adobe.cq.sightly.WCMUsePojo;
public class MultiFieldJsonHelper extends WCMUsePojo {
 private String[] json;
 private static final Logger LOG = LoggerFactory.getLogger(MultiFieldJsonHelper.class);
 @Override
 public void activate() throws Exception {
  String resPath = get("resPath", String.class);
  String prop = get("prop", String.class);
  if (resPath != null && prop != null) {
   Resource res = getResourceResolver().getResource(resPath);
   ValueMap vm = res.getValueMap();
   json = vm.get(prop, String[].class);
  }
 }
 public List<Map<String, String>> getValues() {
  List<Map<String, String>> results = new ArrayList<Map<String, String>>();
  if (json != null) {
   for (String value : json) {
    Map<String, String> column = parseItem(value);
    if (column != null) {
     results.add(column);
    }
   }
  }
  return results;
 }
 private Map<String, String> parseItem(String value) {
  Map<String, String> columnMap = new HashMap<String, String>();
  JSONObject parsed;
  try {
   parsed = new JSONObject(value);
   for (Iterator<String> iter = parsed.keys(); iter.hasNext();) {
    String key = iter.next();
    String innerValue = parsed.getString(key);
    columnMap.put(key, innerValue);
   }
   return columnMap;
  } catch (JSONException e) {
   LOG.info("JSONException occured {}", e.getMessage());
  }
  return null;
 }
}

Reading in HTL (Sighlty) Component
<ul data-sly-use.multiFieldJsonHelper="${'MultiFieldJsonHelper' @resPath=resource.path,prop='products'}">
   <sly data-sly-list.product="${multiFieldJsonHelper.values}">
  <li class="${product['cssClass']} col-lg-6 col-xs-6">
   <img src="${product['productImagePath']}" alt="${product['productImgAltText'] @ i18n}" />
   </li>
 <sly>
</ul>


By aem4beginner

No comments:

Post a Comment

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