Custom autocomplete

Description

Example of a more customizable autocomplete than the default implementation. It allows you to define the HTML body that we want to show for each option. You can have a look at tapestry5-xtensions library.

Demo

Try to write Brownie or Omelette...

Source codes

package es.carlosmontero.webapp.t5devutil.pages.components;

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

import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PageRenderLinkSource;

import es.carlosmontero.webapp.t5devutil.util.ModelObject;

@Import(module = "autocomplete", stylesheet = "css/file1.css")
public class AutocompletePage {

   public static final List<ModelObject> MODEL_OBJECTS;

   static {

      MODEL_OBJECTS = new ArrayList<ModelObject>();
      MODEL_OBJECTS.add(new ModelObject(0, "Brownie", "Special compact cake with walnuts",
              "http://elcocinerocasero.com/imagen/receta/200/200/2015-12-28-13-10/brownie-de-chocolate.jpeg"));

      MODEL_OBJECTS
              .add(new ModelObject(
                      1,
                      "Spanish omelette",
                      "It is one of the typical dishes of Spanish cuisine that stands out is so tasty and the simplicity of its ingredients.",
                      "http://elcocinerocasero.com/imagen/receta/200/200/2016-05-04-10-39/tortilla-de-patata.jpeg"));

   }

   @Inject
   private PageRenderLinkSource pageRenderLinkSource;

   @Property
   private String text, text2;

   public List<Map<String, String>> onCompletionsRequestedFromText(final String partial) {

      final List<Map<String, String>> result = new ArrayList<Map<String, String>>();

      for (final ModelObject mo : MODEL_OBJECTS) {
         if (mo.getName().toLowerCase().contains(partial.toLowerCase())) {
            final Map<String, String> match = new HashMap<String, String>();
            match.put("name", mo.getName());
            match.put("link",
                    pageRenderLinkSource.createPageRenderLinkWithContext(AutocompleteResultPage.class, mo.getId())
                            .toAbsoluteURI());
            match.put("desc", mo.getDescription());
            match.put("imageUrl", mo.getImageUrl());

            result.add(match);
         }
      }

      return result;
   }

}