Saturday, November 8, 2014

jQuery autocomplete in Liferay 6.2

Hi! today I'll show how to use the jQuery autocomplete functionality in Liferay 6.2.

The result will be shown on a page with an autocomplete input for books titles under what I'll show a search-container with the possible books to be found.





For that I'll use a custom table in the database with the following fields:

    <entity name="Book" local-service="true" remote-service="false">

        <column name="bookId" type="long" primary="true" />
        <column name="title" type="String" />

        <column name="groupId" type="long" />

        <column name="companyId" type="long" />
        <column name="userId" type="long" />
        <column name="userName" type="String" />
        <column name="createDate" type="Date" />
        <column name="modifiedDate" type="Date" />
    </entity>



I'll use jQuery 1.10.4 library for this example with the following imports for javascript and css

<link rel="stylesheet" href="<%=request.getContextPath()%>/js/css/ui-lightness/jquery-ui-1.10.4.min.css">

<script type='text/javascript' src='<%=request.getContextPath()%>/js/jquery-1.10.2.js'></script>
<script type='text/javascript' src='<%=request.getContextPath()%>/js/jquery-ui-1.10.4.min.js'></script>      


An additional jsp page will be needed to retrieve the books data, so I'll create a render URL to reference it.

<portlet:renderURL var="loadBooksURL" windowState="<%= LiferayWindowState.EXCLUSIVE.toString() %>">
       <portlet:param name="jspPage" value="/selectBooks.jsp"></portlet:param>
</portlet:renderURL>



The input field that will be filled with data goes in the following way:

<div class="ui-widget">
<label for="bookTitle">Title</label>
<input id="bookTitle" name="bookTitle"/>
</div>


And, finally, the call to the jquery autocomplete function:

<script type="text/javascript">

    $(document).ready(function() {  
        $('#bookTitle').autocomplete({
            source: function(request, response) {
                 $.ajax({
                      url : '<%=loadBooksURL%>',
                      dataType : 'json',
                      data : {
                          term : request.term
                      },
                      success : function(data) {
                          response($.map(data, function(item) {
                              return {
                                    label : item.title,
                                    value : item.title,
                                    id   :  item.bookId
                              }
                       }))

                       }                              
                     })
               }
        });

    });
</script>

Additionally, we can define funcions for other events such us "select", "close" or "change", to specify what will happen when we choose and option, close the list , there is a change in the input, etc.


The next step is to create the selectBooks.jsp file. I'll use the JSONSerializer class to make it easier, but I could create the JSON response structure on my own.

With this code, jQuery will create a "term" parameter into the HttpServletRequest object, so we have to retieve it from the request before doing the search.

The code is the following:

<%
       HttpServletRequest httpReq = PortalUtil.getOriginalServletRequest(
                                                                           PortalUtil.getHttpServletRequest(renderRequest));
       String term = httpReq.getParameter("term");

       List<Book> books = BookLocalServiceUtil.findByTitle(term);

       JSONSerializer serializer = JSONFactoryUtil.createJSONSerializer();

       serializer.include("books");
%>

<%=serializer.serialize(books)%>


And that's all. I already have my book's title autocomplete input!


No comments:

Post a Comment