Searchable comboboxes


Comboboxes, ie. html <select>, are not searchable by default. This is only ok for very short lists.

After a short search i found the https://select2.org/ which was quite easy to use with Grails. I will walk through the steps needed to make it work in a new project.

First create an application to run the test with.

grails create-app combobox

Open the project, then open build.gradle:

// insert before version
plugins {
    id 'com.craigburke.client-dependencies' version '1.4.0'
}
// append at end
clientDependencies {
    yarn {
        'select2'('4.0.13')
    }
}

Build the project. You will find that both css and js have been imported to the project:

Open application.css and insert before require_self:

*= require select2/css/select2.css

Open application.js and insert require before require_self. $(doc… should be appended:

//= require select2/js/select2.js

$(document).ready(function() {
    $('.prpr-select').select2();
});

Now testing this we’ll need a domain and a controller.

grails create-domain-class test.Customer

like this:

package test

class Customer {

    static constraints = {
    }

    String name
    String type
    
}

Generate controller and views:

grails generate-all test.Customer

Open views/customer/create.gsp and look for <f:all bean=”customer”/>

<%--                    <f:all bean="customer"/>--%>
                    <f:with bean="customer">
                        <f:field property="name"/>
                        <f:field property="type">
                            <g:select name="type" 
                                      from="['Small company', 'Medium company', 'Government', 'Private person']" 
                                      class="prpr-select"/>
                        </f:field>
                    </f:with>

Test run and create a customer.

,