liferay search container pagination issue - liferay

This is my Liferay search container code:
MVC:BigInteger leaveTotalCount;
ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
PortletURL iteratorURL = PortletURLFactoryUtil.create(request, themeDisplay.getPortletDisplay().getId(),
themeDisplay.getPlid(), PortletRequest.RENDER_PHASE);
SearchContainer<LeaveDetailsWrapper> searchContainer = null;
searchContainer = new SearchContainer<>(request, null, null, SearchContainer.DEFAULT_CUR_PARAM,
SearchContainer.DEFAULT_DELTA, iteratorURL, null, LmsLeaveDashboardConstant.BLANK_STRING);
List<LeaveDetailsWrapper> leaveDetails;
try {
searchContainer.setDeltaConfigurable(true);
leaveDetails = leaveLocalService.getLeaveDetails(null, null, null, null,
LmsLeaveDashboardUtils.getEmpCode(request), searchContainer.getStart(), searchContainer.getEnd());
log.info(leaveDetails);
leaveTotalCount = leaveLocalService.getLeaveDetailsCount(null, null, null, null,
LmsLeaveDashboardUtils.getEmpCode(request), -1, -1);
searchContainer.setEmptyResultsMessage("No Data Found..!");
searchContainer.setTotal(leaveTotalCount.intValue());
searchContainer.setIteratorURL(iteratorURL);
searchContainer.setResults(leaveDetails);
} catch (Exception e) {
log.error("ERROR:IntrahrmsLmsLeaveDashboardWebPortlet leaveSearchContianer" + e);
}
return searchContainer;
jsp:
<liferay-ui:search-container searchContainer="${leaveInfoContainer}" iteratorURL="${iteratorURL}">
<liferay-ui:search-container-results
results="${leaveInfoContainer.getResults()}" />
<liferay-ui:search-container-row
className="com.intrahrms.lms.service.leavecustom.model.LeaveDetailsWrapper"
modelVar="LeaveDetails">
<liferay-ui:search-container-column-text
value="${LeaveDetails.leaveTypeName} Leave " name="Leave Type" />
<liferay-ui:search-container-column-text name="From Date">
<fmt:formatDate pattern="dd/MM/yyyy"
value="${LeaveDetails.fromDate}" type="date" />
</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text name="To Date">
<fmt:formatDate pattern="dd/MM/yyyy" value="${LeaveDetails.toDate}"
type="date" />
</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text
value="${LeaveDetails.totalDays}" name="Total Leave Days" />
<liferay-ui:search-container-column-text name="Applied Date">
<fmt:formatDate pattern="dd/MM/yyyy"
value="${LeaveDetails.appliedDate}" type="date" />
</liferay-ui:search-container-column-text>
<liferay-ui:search-container-column-text
value="${LeaveDetails.leaveStatus} " name="Status" />
<liferay-ui:search-container-column-text
value="${LeaveDetails.projectManagerId}" name="Reporting Manager" />
<liferay-ui:search-container-column-jsp path="/action.jsp"
align="center" />
</liferay-ui:search-container-row>
<liferay-ui:search-iterator markupView="lexicon" />
</liferay-ui:search-container>
The problem is when I'm changing a pagination or change delta, it gives me whole record instead of filter record.

Your search container seems to be doing the right thing as:
leaveDetails = leaveLocalService.getLeaveDetails(null, null, null, null,
LmsLeaveDashboardUtils.getEmpCode(request), searchContainer.getStart(), searchContainer.getEnd());
Think about this: you have just created the instance, what would you expect to be in start and end?
When you created your containers you told it about the parameters it shoudl use, but they are not being set on your JSP, for instance:
<liferay-ui:search-container emptyResultsMessage="there-are-no-file-entries" iteratorURL="${filesRenderUrl}" delta="${files_searchDelta}" total="${files_searchTotal}" curParam="files" deltaParam="files">
bottom line, if you want to control your search container in java methods like that, you will need to act accordingly to set your results:
private static int getStart( int current, int delta ) {
return ( current - 1 ) * delta;
}
private static int getEnd( int first, int delta ) {
return first + delta;
}

Related

Render()'s Method different reactions

I have my render() method with no code.
And I have this action-method:
#ProcessAction(name = "viewBook")
public void viewBook(ActionRequest actionRequest,ActionResponse actionResponse) throws SystemException, PortalException {
long bookId = ParamUtil.getLong(actionRequest, "bookId");
Book book = BookLocalServiceUtil.getBook(bookId);
actionRequest.setAttribute(FinalStrings.BOOK_ENTRY, book);
actionResponse.setRenderParameter("jspPage", "/html/LibraryPortlet/view_book.jsp");
How can I rewrite this "GET" method into render() method? I mean I need to run
public void render(RenderRequest renderRequest, RenderResponse rendeResponse){
super.render(renderRequest, renderResponse)
}
in the default situation and
public void render(RenderRequest renderRequest, RenderResponse rendeResponse){
\\THIS CODE IS NOT WORKING, IT'S JUST TO SHOW WHAT I WANT!
long bookId = ParamUtil.getLong(actionRequest, "bookId");
Book book = BookLocalServiceUtil.getBook(bookId);
actionRequest.setAttribute(FinalStrings.BOOK_ENTRY, book);
actionResponse.setRenderParameter("jspPage", "/html/LibraryPortlet/view_book.jsp");
when I need to use viewBook() method. How can I parametrize(?) render() method?
Update:
For more details I attached one screenshot:
Meanwhile in my action.jsp:
<liferay-ui:icon-menu>
<portlet:actionURL name="deleteBook" var="deleteURL">
<portlet:param name="bookId"
value="${String.valueOf(book.getBookId())}" />
</portlet:actionURL>
<portlet:renderURL name="viewBook" var="viewURL">
<portlet:param name="bookId"
value="${String.valueOf(book.getBookId())}" />
</portlet:renderURL>
<portlet:renderURL var="editBookURL" name="viewEdit">
<portlet:param name="bookId" value="${String.valueOf(book.getBookId())}" />
</portlet:renderURL>
<liferay-ui:icon image="add" message="View" url="${viewURL.toString()}" />
<liferay-ui:icon image="add" message="Edit" url="${editBookURL.toString()}" />
<liferay-ui:icon-delete image="delete" message="Delete" url="${deleteURL.toString()}" />
In my view_book.jsp:
<%#page import="com.softwerke.FinalStrings"%>
<%#page import="com.softwerke.model.Book"%>
<%#page import="com.softwerke.service.BookLocalServiceUtil"%>
<%#page import="com.liferay.portal.kernel.util.ParamUtil"%>
<%# include file="/html/init.jsp"%>
<portlet:renderURL var="backURL">
<portlet:param name="jspPage" value="/html/view.jsp"/>
</portlet:renderURL>
<liferay-ui:header backURL="${backURL}" title="Back" />
<%
Book book = (Book) request.getAttribute(FinalStrings.BOOK_ENTRY);
%>
<aui:form>
<aui:model-context bean="${book}" model="${Book.class}" />
<aui:input name="bookName" label="Book Name" disabled="true"/>
<aui:input type="textarea" name="description" label="Description" disabled="true"/>
<aui:input name="authorName" label="Author Name" disabled="true"/>
<aui:input name="price" label="Price" disabled="true"/>
</aui:form>
According to my task I can not use Action URL here. What should I do???
You can send a command param to the render, so you can split the logic into two or more render methods, depending on the command, or maybe easier, invoke a mvcPath without the need of implementing anything in render(). Include something like this in the jsp with your list of books:
<portlet:renderURL var="myBookURL">
<portlet:param name="mvcPath" value="/view_book.jsp" />
<portlet:param name="bookId" value="<%= someBookId %>" />
</portlet:renderURL>
View My Book
You just need a view_book.jsp with something like:
<%
long bookId = ParamUtil.getLong(request, "bookId");
Book book = BookLocalServiceUtil.getBook(bookId);
%>
Hope it helps.

What is the best way avoid reload the jsp page?

enter image description hereHere is my jsp code
<portlet:renderURL var="rssSearchResult">
<portlet:param name="<%=CMD.ACTION%>"
value="<%=RenderKeys.FIND_CONTENT_SEARCH%>" />
<%-- <portlet:param name="categoryId" value="<%=String.valueOf(category.getCategoryId())%>"/> --%>
<div id="category-content" class="span8">
<aui:form render="<%=rssSearchResult %>">
<aui:input placeholder="Please Enter RSS Feed Title Here"
name="search" label="" id="searchTitle" type="text"
style="width:300px;" />
<aui:button type="button" name="search" id="searchTitle" value="submit" class="Find_content_search"
onclick="javascript:mynav('<%=rssSearchResult%>');addinMoveableBar();"></aui:button>
</aui:form>
*************Here is my java source code************
#RenderMapping(params=CMD.ACTION+StringPool.EQUAL+RenderKeys.FIND_CONTENT_SEARCH)
public void rssSearchResult(RenderRequest renderRequest,
RenderResponse renderResponse) {
String searchValue= ParamUtil.getString(renderRequest, "search");
DynamicQuery SearchaQuery = DynamicQueryFactoryUtil.forClass(
AssetEntry.class, PortletClassLoaderUtil.getClassLoader());
SearchaQuery.add(PropertyFactoryUtil.forName("title").eq(searchValue));
try {
List<AssetEntry> assentries=AssetEntryLocalServiceUtil.dynamicQuery(SearchaQuery);
List<AssetCategory> assetcategory=null;
for(AssetEntry assetentry:assentries){
assetcategory= AssetCategoryLocalServiceUtil.getAssetEntryAssetCategories(assetentry.getEntryId(), -1, -1);
}
renderRequest.setAttribute("AssetCategory", assetcategory);
renderRequest.setAttribute("AssetEntries", assentries);
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*************main.js***************
function mynav(navurl){
ajaxindicatorstart("Processing Please Wait");
loadPage(navurl);
history.pushState({}, '', navurl);
}
I have a search text box with submit button if i search title of category it has to be display without reloading the page....

Liferay search container in Spring MVC portlets

Is it possible to use Liferay search container in spring portlets? when i tried, nothing is rendering in the page. i have enclosed the code. am just adding the data in session and trying to show in search container.
<%
final PortletSession sessData = renderRequest.getPortletSession();
List<Detail> details = (List<Detail>) sessData.getAttribute("DETAILS",PortletSession.PORTLET_SCOPE);
%>
<liferay-ui:search-container delta="3" emptyResultsMessage="No Details found" headerNames="User ID, First Name, Last Name, Address">
<%
int numOfRecords = details.size();
%>
<liferay-ui:search-container-results results="<%= details %>" total="${numOfRecords}">
</liferay-ui:search-container-results>
<liferay-ui:search-container-row className="Detail" modelVar="detailData">
<liferay-ui:search-container-column-text name="User ID" property="userId" />
<liferay-ui:search-container-column-text name="First Name" property="firstName" />
<liferay-ui:search-container-column-text name="Last Name" property="lastName" />
<liferay-ui:search-container-column-text name="Address" property="address" />
</liferay-ui:search-container-row>
</liferay-ui:search-container>
I missed to add the search-iterator.
<liferay-ui:search-iterator searchContainer="<%=searchContainer%>"
paginate="<%=isNeeded%>" />

Liferay: How to place values (or not lose values) in ParamUtil in case of exception?

I am new to developing on Liferay and am currently using Liferay 6.2 on Eclipse Kepler IDE.
I am currently making a small webpage based on the following view & add/update example in the development guide
In the example the method paramUtil.getLong(long) is used to pass the id of the row to be updated to the add/update page.
My issue is that when an exception occurs (on the back end) this data is lost and the page changes to an add entry page.
How do I retain the data sot that ParamUtil can retrieve it when an exception is thrown on the back end?
I have included snippets of the example front end code below.
VIEW.JSP:
<liferay-ui:search-container-row
className="com.nosester.portlet.eventlisting.model.Location"
keyProperty="locationId"
modelVar="location" escapedModel="<%= true %>"
>
<liferay-ui:search-container-column-text
name="name"
value="<%= location.getName() %>"
/>
<liferay-ui:search-container-column-text
name="description"
value="<%= location.getDescription() %>"
/>
<liferay-ui:search-container-column-text
name="streetAddress"
value="<%= location.getStreetAddress() %>"
/>
<liferay-ui:search-container-column-text
name="city"
value="<%= location.getCity() %>"
/>
<liferay-ui:search-container-column-text
name="stateOrProvince"
value="<%= location.getStateOrProvince() %>"
/>
<liferay-ui:search-container-column-text
name="country"
value="<%= location.getCountry() %>"
/>
<liferay-ui:search-container-column-jsp
align="right"
path="/html/locationlisting/location_actions.jsp"
/>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
ACTIONS.JSP
<%
ResultRow row = (ResultRow) request
.getAttribute(WebKeys.SEARCH_CONTAINER_RESULT_ROW);
Location location = (Location) row.getObject();
long groupId = location.getGroupId();
String name = Location.class.getName();
long locationId = location.getLocationId();
String redirect = PortalUtil.getCurrentURL(renderRequest);
%>
<liferay-ui:icon-menu>
<portlet:renderURL var="editURL">
<portlet:param name="mvcPath" value="/html/locationlisting/edit_location.jsp" />
<portlet:param name="locationId" value="<%= String.valueOf(locationId) %>" />
<portlet:param name="redirect" value="<%= redirect %>" />
</portlet:renderURL>
<liferay-ui:icon image="edit" url="<%= editURL.toString() %>" />
EDIT.JSP
<%
Location location = null;
long locationId = ParamUtil.getLong(request, "locationId");
if (locationId > 0) {
location = LocationLocalServiceUtil.getLocation(locationId);
}
String redirect = ParamUtil.getString(request, "redirect");
%>
<aui:model-context bean="<%= location %>" model="<%= Location.class %>" />
<portlet:renderURL var="viewLocationURL" />
<portlet:actionURL name='<%= location == null ? "addLocation" : "updateLocation" %>' var="editLocationURL" windowState="normal" />
<liferay-ui:header
backURL="<%= viewLocationURL %>"
title='<%= (location != null) ? location.getName() : "New Location" %>'
/>
<aui:form action="<%= editLocationURL %>" method="POST" name="fm">
<aui:fieldset>
<aui:input name="redirect" type="hidden" value="<%= redirect %>" />
<aui:input name="locationId" type="hidden" value='<%= location == null ? "" : location.getLocationId() %>'/>
<aui:input name="name" />
<aui:input name="description" />
<aui:input name="streetAddress" />
<aui:input name="city" />
<aui:input name="stateOrProvince" />
<aui:input name="country" />
</aui:fieldset>
<aui:button-row>
<aui:button type="submit" />
<aui:button onClick="<%= viewLocationURL %>" type="cancel" />
</aui:button-row>
UPDATE 1:
Adding back end logic as requested by Parkash Kumar:
LocationListingPortlet.java (Link to Example from Document)
public void updateLocation(ActionRequest request, ActionResponse response)
throws Exception {
_updateLocation(request);
sendRedirect(request, response);
}
private Location _updateLocation(ActionRequest request)
throws PortalException, SystemException {
long locationId = (ParamUtil.getLong(request, "locationId"));
String name = (ParamUtil.getString(request, "name"));
String description = (ParamUtil.getString(request, "description"));
String streetAddress = (ParamUtil.getString(request, "streetAddress"));
String city = (ParamUtil.getString(request, "city"));
String stateOrProvince = (ParamUtil.getString(request, "stateOrProvince"));
String country = (ParamUtil.getString(request, "country"));
ServiceContext serviceContext = ServiceContextFactory.getInstance(
Location.class.getName(), request);
Location location = null;
if (locationId <= 0) {
location = LocationLocalServiceUtil.addLocation(
serviceContext.getUserId(), serviceContext.getScopeGroupId(), name, description,
streetAddress, city, stateOrProvince, country, serviceContext);
}
else {
location = LocationLocalServiceUtil.getLocation(locationId);
location = LocationLocalServiceUtil.updateLocation(
serviceContext.getUserId(), locationId, name,
description, streetAddress, city, stateOrProvince, country,
serviceContext);
}
return location;
}
private static Log _log = LogFactoryUtil.getLog(LocationListingPortlet.class);
}
In-case exception occurs, handle it in _updateLocation and reset required parameters in catch, as following:
Location location = null;
try {
if (locationId <= 0) {
location = LocationLocalServiceUtil.addLocation(
serviceContext.getUserId(), serviceContext.getScopeGroupId(),
name, description, streetAddress, city, stateOrProvince,
country, serviceContext);
} else {
location = LocationLocalServiceUtil.getLocation(locationId);
location = LocationLocalServiceUtil.updateLocation(
serviceContext.getUserId(), locationId, name,
description, streetAddress, city, stateOrProvince, country,
serviceContext);
}
}catch(Exception ex){
_log.error(ex);
// set render parameters
request.setRenderParameter("locationId", locationId);
}

Update row in Gridview?

I have updated a row in Gridview but it is not working.
Here is my code :
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
//Label lbldeleteid = (Label)row.FindControl("Label1");
string bname= GridView1.DataKeys[e.RowIndex].Values["manufacturer"].ToString();
TextBox tbmanu = (TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[1];
var myString = tbmanu.ToString();
SqlCommand cmd = new SqlCommand("manu_upd",con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#manufacturer", SqlDbType.NVarChar,100);
cmd.Parameters["#manufacturer"].Value = myString;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
I got the following error :
Unable to cast object of type 'System.Web.UI.LiteralControl' to type
'System.Web.UI.WebControls.TextBox'.
here is my Grid view :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="manufacturer" ForeColor="#333333"
GridLines="None" Width="400px" BorderStyle="Double"
CellSpacing="3" Font-Bold="True" Font-Size="Small" ShowFooter="True"
ShowHeaderWhenEmpty="True" onrowdeleting="GridView1_RowDeleting"
onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating"
onrowcancelingedit="GridView1_RowCancelingEdit"
AutoGenerateEditButton="True">
<AlternatingRowStyle BackColor="White"/>
<Columns>
<asp:TemplateField HeaderText="Number" ItemStyle-
HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lbnaumber" runat="server" Text='<%#
Container.DataItemIndex + 1 %>'></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Manufacturer"
SortExpression="manufacturer">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#
Bind("manufacturer") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="tbmanu" runat="server" Text='<%#
Bind("manufacturer") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<%--<asp:CommandField ShowEditButton="True" />--%>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<EditRowStyle BackColor="#2461BF"/><FooterStyle BackColor="#507CD1"
Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"/>
<PagerStyle BackColor="#2461BF" ForeColor="White"
HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" /><SelectedRowStyle BackColor="#D1DDF1"
Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB"/>
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
When I change the index of my text box 1 to 3 it shows me below error :
Specified argument was out of the range of valid values.
Parameter name: index
When i change its index 3 to 2 it gives me below error :
Unable to cast object of type 'System.Web.UI.WebControls.DataControlLinkButton' to type 'System.Web.UI.WebControls.TextBox'.
I have one required field validator in my form but when I enable that validation update in grid view is not working.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
TextBox tbmanu1 = (TextBox)row.FindControl("tbmanu");
//or try
//TextBox tbmanu1= (TextBox)row.Cells[0].FindControl("tbmanu");
string myString = Convert.Tostring(tbmanu1.text);
cmd.Parameters["#manufacturer"].Value = myString;
}
Try wrapping your gridview in a asp:UpdatePanel and set the update mode to conditional.
Good Luck

Resources