Last updated by 5 years ago

Page: Searchable Plugin - SearchableController and view, Version:0

SearchableController and view

Searchable Plugin comes with a controller (SearchableController) and view (searchable/index.gsp) to demonstrate displaying results and pagination. Try these with your application (like this) - they may help to test queries and you can probably copy some of the code.

You will probably want to change the URL and the view at least.

To change the URL add entries to your UrlMappings.

To change the view, you can simply keep the plugin's controller and copy myapp/plugins/searchable-x.x/grails-app/views/searchable/index.gsp to myapp/grails-app/views/searchable/index.gsp, where it will override the plugin's version, or you could create your own new controller and view of course.

Under the covers

Here's the implementation of the search action from SearchableController:

import org.compass.core.engine.SearchEngineQueryParseException

// ...

class SearchableController { def searchableService

/** * Index page with search form and results */ def index = { if (!params.q?.trim()) { return [:] } try { return [searchResult: searchableService.search(params.q, params)] } catch (SearchEngineQueryParseException ex) { return [parseException: true] } }

// … }

Notice that params.q is the search query string and params is also given to SearchableService#search as the second argument, which is a Map of options (see Searching). These options are things like page size, start result no, etc.

(Any String arguments are parsed, so you can use request parameters directly, even when they have string values (for example, params may be [escape: "true", offset: "20"], but you won't get a ClassCastException).)

Pagination of search results in the view

Search results can be paginated using Grail's standard {{<g:paginate />}} tag.

Here it is in action in the Searchable Plugin's own search results page, {{{}grails-app/views/searchable/index.gsp{}}}. Note {{{}searchResult{}}} is an object returned by one of the {{{}SearchableService{}}} or domain class {{{}search{}}} methods:

<g:if test="${haveResults}"> <!-- or you could use test="${searchResult?.results}" -->
    Page:
    <g:set var="totalPages" value="${Math.ceil(searchResult.total / searchResult.max)}" />
    <g:if test="${totalPages == 1}"><span class="currentStep">1</span></g:if>
    <g:else><g:paginate controller="searchable" action="index" params="[q: params.q]" total="${searchResult.total}" prev="&lt; previous" next="next &gt;"/></g:else>
</g:if>
And here is some basic CSS to style the generated HTML:
.paging a.step {
    padding: 0 .3em;
}

.paging span.currentStep { font-weight: bold; }

A future release will provide more help with building your own controllers and views.

{section} {column:width=30%} {column} {column:width=30%} Up - Searchable Plugin {column} {column:width=30%} Next - Searching {column} {section}