Skip to content

Instantly share code, notes, and snippets.

@gabrielwalt
Last active July 22, 2020 21:31
Show Gist options
  • Save gabrielwalt/8dd12b83904058474650 to your computer and use it in GitHub Desktop.
Save gabrielwalt/8dd12b83904058474650 to your computer and use it in GitHub Desktop.
Sightly and SlingModel example that searches for commerce products with specific tags in "/etc"
<ul data-sly-use.directory="org.summit.lab.core.models.ProductDirectory"
data-sly-list="${directory.results}">
<li>${item.properties.jcr:title}</li>
</ul>
package org.summit.lab.core.models;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.models.annotations.Model;
import com.day.cq.search.PredicateGroup;
import com.day.cq.search.Query;
import com.day.cq.search.QueryBuilder;
import com.day.cq.search.result.Hit;
@Model(adaptables=Resource.class)
public class ProductDirectory {
public Iterator<Hit> results;
@Inject
private ResourceResolver resourceResolver;
@Inject
private QueryBuilder queryBuilder;
@PostConstruct // This is called after all the injection has occurred
private void searchProducts() throws RepositoryException {
final Map<String, String> map = new HashMap<String, String>();
map.put("path", "/etc");
map.put("1_property", "cq:commerceType");
map.put("1_property.value", "product");
map.put("2_property", "cq:tags");
map.put("2_property.value", "geometrixx-outdoors:activity/hiking");
Query query = queryBuilder.createQuery(PredicateGroup.create(map), resourceResolver.adaptTo(Session.class));
results = query.getResult().getHits().iterator();
}
}
@kmrobin
Copy link

kmrobin commented Jul 13, 2017

Hi Gabriel,
This is a very useful example and demonstration of how much less code is required with sightly.

Just wondering, in the above example, if there's a simple way to pass the tag parameter (geometrixx-outdoors:activity/hiking) dynamically from html file to the ProductDirectory class.
I got the request object by various ways of injecting but that doesn't seem to be the one containing the request parameters.

I don't want to write it the ajax way around but read some where in the forum that request parameters can't be passed to sling models.
May be some little hack to pass as context parameter or something ?

Thank you for the help!

Robin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment