Multivalue AutoComplete for Tapestry

I have been very experimenting with tapestry-jquery plugin and it is great to finally go back to jquery. Not only using jquery is very easy but it also comes with a lot of plugins.

There are some improvements that I think can be added to the tapestry-jquery integration but don’t get time to discuss them in the mailing list.

Recently I wanted to use a multivalue autocomplete something on the lines of and found a wonderful plugin

So here is a multi-value auto-complete plugin. Is there anything easier than Tapestry ?

        library = "jquery.tokeninput.js",
        stylesheet = "token-input.css"
public class AutoComplete extends AbstractField {

    @Parameter(autoconnect = true, required = true)
    private List<Object> values;

    @Parameter(required = true)
    private ValueEncoder encoder;

    private ComponentResources resources;

    private JavaScriptSupport javaScriptSupport;

    private LabelProvider labelProvider;

    private FieldValidationSupport fieldValidationSupport;

    @Parameter(defaultPrefix = BindingConstants.VALIDATE)
    private FieldValidator<Object> validator;

    LabelProvider defaultLabelProvider() {
        return new LabelProvider() {

            public String getLabel(Object value) {
                return value.toString();

    private Request request;

    private ValidationTracker tracker;

    protected void processSubmission(String controlName) {
        String parameterValue = request.getParameter(controlName);

        this.tracker.recordInput(this, parameterValue);

        if (values == null) {
            values = new ArrayList<Object>();
        } else {

        for (String value : TapestryInternalUtils.splitAtCommas(parameterValue)) {


        if (validator != null) {
            try {
                fieldValidationSupport.validate(values, resources, validator);
            } catch (final ValidationException e) {
                this.tracker.recordError(this, e.getMessage());


    void writeFieldTag(MarkupWriter writer) {
                "type", "text",
                "name", getControlName(),
                "id", getClientId());

    void afterRender(MarkupWriter writer) {

        JSONObject parameters = getInformalParametersAsJSON();


        javaScriptSupport.addScript("$('#%s').tokenInput('%s', %s);",
                getClientId(), getCallbackURL(), parameters

    private JSONObject getInformalParametersAsJSON() {
        JSONObject json = new JSONObject();

        for (String param : resources.getInformalParameterNames()) {
            json.put(param, resources.getInformalParameter(param,

        return json;

    private void loadCurrentValues(JSONObject parameters) {
        if (values != null) {
            parameters.put("prePopulate", toJSON(values));

    private String getCallbackURL() {
        return resources.createEventLink("provideList").toAbsoluteURI();

    JSONArray provideCompletion(@RequestParameter("q") String queryParams) {
        CaptureResultCallback<List<?>> callback = new CaptureResultCallback<List<?>>();

        boolean wasTriggered = resources.triggerEvent(
                new Object[]{queryParams},

        if (!wasTriggered) {
            throw new RuntimeException("Event '" + 
                    ExtensionEvents.PROVIDE_COMPLETION "' must be handled"));

        return toJSON(callback.getResult());

    private JSONArray toJSON(List<?> list) {
        JSONArray array = new JSONArray();
        for (Object value : list) {
            JSONObject params = new JSONObject();
            params.put("id", encoder.toClient(value));
            params.put("name", labelProvider.getLabel(value));

        return array;


public interface LabelProvider<T> {
    String getLabel(T value);

public class ExtensionEvents {
    public static final String PROVIDE_COMPLETION = "provideCompletions";



    <t:if test='fruits'>

    <form t:type='Form' t:id='Form' action=''>
        <label t:for='fruit' t:type='Label'/>
        <input type='text' t:encoder='encoder' t:type='xeric/AutoComplete' t:id='fruit'

        <input type='submit' value='submit'/>

public class AutoCompleteDemo {

    private List<Fruit> fruits;

    private TypeCoercer typeCoercer;

    void activate() {
        if (fruits == null) {
            fruits = new ArrayList<Fruit>();

    public ValueEncoder<?> getEncoder() {
        return new EnumValueEncoder<Fruit>(typeCoercer, Fruit.class);

    List<Fruit> provideCompletion(String query) {
        List<Fruit> fruits = new ArrayList<Fruit>();

        for (Fruit fruit : Fruit.values()) {
            if ( {

        return fruits;

public enum Fruit {

About these ads

Tagged: , , ,

3 thoughts on “Multivalue AutoComplete for Tapestry

  1. Howard M. Lewis Ship (@hlship) December 30, 2011 at 10:01 PM Reply

    Could you add a screen shot of you component in action? Also, please add Durian as one of your fruits. Thanks!

  2. uklance January 12, 2012 at 6:37 PM Reply

    Wow… this is a really useful component for making a user friendly UI. A couple of questions:
    1. Lets consider that Fruit was a hibernate entity, not an enum, with a name and an id. In this case, what would be sent to the server? Would it be the name or the id?
    2. Is it possible to use the return type from provideCompletion(String query) to determine which class to pass to the typeCoercer and remove the need for getEncoder()?

    • George May 16, 2012 at 7:56 PM Reply

      Lance, did you ever get answers to your questions?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 90 other followers

%d bloggers like this: