Granite Autocomplete list with query not returning
I am trying to use the autocomplete field to do a lookup connected with an external API. In classic I could link the options list of a select field to a path and implement a servlet to do that work. But I'm struggling to get the same working in Touch UI / Granite.
<product jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/coral/foundation/form/autocomplete"
emptyText="Search for an item"
fieldLabel="Product"
name="./productId">
<options jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/coral/foundation/form/autocomplete/list"
src="/apps/foo/datasources/product.html{?query,start,end}"/>
</product>
This is calling into a servlet successfully. However I've implemented placeholder code to return the JSON response I believe is required and it doesn't render. Instead the list of matches is empty.
@SlingServlet(
paths = { ProductLookupDatasource.PATH },
methods = "GET")
public class ProductLookupDatasource extends SlingSafeMethodsServlet {
protected static final String PATH = "/apps/foo/datasources/product";
private static final Logger LOG = LoggerFactory.getLogger(ProductLookupDatasource.class);
@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
throws IOException {
String query = request.getParameter("query");
LOG.info("Got request params [query: {}]", query);
/* PoC with example content */
try {
JSONArray results = new JSONArray();
for (int i = 0; i < 5; i++) {
JSONObject item = new JSONObject();
item.put("text", "value" + i);
item.put("value", "value" + i);
results.put(item);
}
response.setContentType("application/json;charset=UTF-8");
response.getWriter().print(results.toString());
} catch (JSONException e) {
throw new IOException(e);
}
}
}
The query is logged correctly, so I will be able to make the call out to the service and get the real data. After 0.2 seconds further queries are made, so if I type in I'm getting the autocomplete experience from the front-end. If I was able to see results back, it could deliver what I need.
But how should I return data? I've tried a few variations on the response including a "content" object with an "innerHTML" attribute and none of them have worked to populate the response. What format is required?
I also have a second concern, that the value written in the JCR will only keep the product ID and not the display name. Is there a way of keeping both the display text and the id? In the examples I've found, this is only used for tags, which have a built in datasource. I've not found any examples with a bespoke datasource. Please advise.