April 7, 2020
Estimated Post Reading Time ~

Implement DataSource for drop down using Sightly AEM 6.1



In the Touch UI component, DataSource is very useful when it comes to populating dropdown 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…


The component contains a simple drop-down, values for this will be populated 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

2. com.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 a new SimpleDataDource object and pass the iterator of our list which contains data.

Here is the AEM Helpx article which shows the same in JSP


By aem4beginner

No comments:

Post a Comment

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