Saturday, 26 March 2016

Implement DataSource for drop down using Sightly AEM 6.1

In Touch UI component, DataSource is very useful when it comes populate drop down dynamically. This article will help you to understand how datasource can be used with Sightly and leaving JSP behind.
Let’s get started with authoring…
Sightly DataSource Component Authoring
Component contains a simple drop down, values for this will be populate dynamically using DataSource.
Here is the code used…
1. DataSource is present at /apps/sightlydatasource/components/content/sample-ds
<sly data-sly-use.data="com.sightlydatasource.core.sightly.SightlyDataSourceExample">
</sly>It simply calls the Java class which act as DataSource
2com.sightlydatasource.core.sightly.SightlyDataSourceExample
package com.sightlydatasource.core.sightly;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceMetadata;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.wrappers.ValueMapDecorator;

import com.adobe.cq.sightly.WCMUse;
import com.adobe.granite.ui.components.ds.DataSource;
import com.adobe.granite.ui.components.ds.SimpleDataSource;
import com.adobe.granite.ui.components.ds.ValueMapResource;

/**
 * Sightly class act as a data source returning dynamic data.
 * 
 * @author Praveen
 */
public class SightlyDataSourceExample extends WCMUse {
 @Override
 public void activate() throws Exception {
  ResourceResolver resolver = getResource().getResourceResolver();

  // Create an ArrayList to hold data
  List<Resource> resourceList = new ArrayList<Resource>();

  ValueMap vm = null;

  for (int i = 1; i <= 5; i++) {
   vm = new ValueMapDecorator(new HashMap<String, Object>());
   String Value = "samplevalue" + i;
   String Text = "Sample Text " + i;
   vm.put("value", Value);
   vm.put("text", Text);

   resourceList.add(new ValueMapResource(resolver,
     new ResourceMetadata(), "nt:unstructured", vm));
  }

  // Create a DataSource that is used to populate the drop-down control
  DataSource ds = new SimpleDataSource(resourceList.iterator());
  this.getRequest().setAttribute(DataSource.class.getName(), ds);
 }

}
Line 45: Create new SimpleDataDource object and pass the iterator of our list which contains data.
Here is the AEM Helpx article which shows same in JSP 
Let me know if you need any help in implementation.

No comments :

Post a comment