Setting the current page in the Liferay Search Container

Initially I wanted to write a tutorial on how to use the liferay search-container. But after I struggeled a lot with forcing the search-container to survive page refreshs I want to share my experience with my audience.

The problem is the following: If you click on a link on a portlet page where a search-container is used the search container is reset. The current page switches back to the first page and your search result is lost. If you take a look at the SearchContainer object yuo´ll find in com.liferay.portal.kernel.dao.search you´ll notice that there is a variable called "_cur" which holds the current page. There is a setter for the variable but no getter ! I don´t know if they forgot to implement it or if this is intended.

Well, here my (hackish) solution to fix this: Implement the method on your own and set the current value when using the search container in your JSP.

First, add the search container to your ext-let (or ext environment in your are using Liferay 5). Second, add the following method:

public void setCur(int cur){
    this._cur = cur;
    _iteratorURL.setParameter(_curParam, String.valueOf(cur));

This makes sure, that the parameter is set and the internal data is processed correctly.
Now deploy you ext and take your portlet. Add the following to your JSP that is using the search-container:

<liferay-ui:search-container emptyResultsMessage="no-entries-were-found"  iteratorURL="<%= portletURL%>" >

<liferay-ui:search-container-results >
<%if (yourOverwrittenCurValue!= -1){

What you do is to set the cur variable with your own value. In my case it´s the variable "yourOverwrittenCurValue".  But how do you get this variable ? The solution is: use the getCur() variable to get the actual value and put it into the session. In your "render" method, retrieve it from the session and provide it to your JSP.

Object curObject= request.getPortletSession().getAttribute("cur");
if (curObject!= null){
request.setAttribute("cur", curObject);
request.getPortletSession().setAttribute("cur", null);

All you have to do now is to retrieve the request value in your JSP and you´re done :)

If you like this tutorial it would be very nice, if you could click on some of the google ads you see on the right side. It helps me run this block and motivates me ;)

If you have any questions, feel free to leave a comment.