Liferay liferay-ui:search-toggle not showing (on search-form) - liferay
I'm trying to create a search form for my portlet.
The portlet is an addressbook application, all dao and service build with service builder.
I would like to give users a basic/advanced search form (like other on liferay, for example on "users and organizations" in control center.
I've implemented all logic and pages looking at liferay source code (6.1 GA1), but the search form is NOT showing up in any way, i'll put the code here.
in view.jsp:
<%
PortletURL portletURL = renderResponse.createRenderURL();
portletURL.setParameter("jspPage", "/html/addressbookportlet/view.jsp");
pageContext.setAttribute("portletURL", portletURL);
String portletURLString = portletURL.toString();
%>
<aui:form action="<%= portletURLString %>" method="get" name="fm">
<liferay-portlet:renderURLParams varImpl="portletURL" />
<aui:input name="isSearch" type="hidden" value="true" />
<aui:input name="redirect" type="hidden" value="<%= portletURLString %>" />
<liferay-ui:search-container
searchContainer="<%= new ABContactSearch(renderRequest, portletURL) %>"
>
<%
ABContactDisplayTerms displayTerms = (ABContactDisplayTerms)searchContainer.getDisplayTerms();
ABContactSearchTerms searchTerms = (ABContactSearchTerms)searchContainer.getSearchTerms();
Long societyId = GetterUtil.getLong(searchTerms.getSocietyId(),0);
Long contactTypeId = GetterUtil.getLong(searchTerms.getContactTypeId(), 0);
Long brandId = GetterUtil.getLong(searchTerms.getBrandId(),0);
Long channelId = GetterUtil.getLong(searchTerms.getChannelId(),0);
%>
<liferay-ui:search-form
searchContainer="<%=searchContainer%>"
servletContext="<%= this.getServletConfig().getServletContext() %>"
showAddButton="true"
page='<%= request.getContextPath() + "/html/addressbookportlet/contact_search_form.jsp" %>'
/>
<liferay-ui:search-container-results>
<%
if (searchTerms.isAdvancedSearch()) {
results = AddressbookSearchUtil.searchAdvanced(scopes, searchTerms, searchTerms.isAndOperator(), searchContainer.getStart(), searchContainer.getEnd()); //, searchContainer.getOrderByComparator());
total = AddressbookSearchUtil.countAdvanced(scopes, searchTerms, searchTerms.isAndOperator());
}
else {
results = AddressbookSearchUtil.searchFullText(scopes, searchTerms.getKeywords(), searchContainer.getStart(), searchContainer.getEnd()); //, searchContainer.getOrderByComparator());
total = AddressbookSearchUtil.countFullText(scopes, searchTerms.getKeywords());
}
pageContext.setAttribute("results", results);
pageContext.setAttribute("total", total);
%>
</liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="it.mir4unicomm.addressbook.model.ABContact"
escapedModel="<%= true %>"
keyProperty="contactId"
modelVar="abcontact"
>
<liferay-ui:search-container-column-text
title="Surname"
property="surname"
/>
<liferay-ui:search-container-column-text
title="Name"
property="name"
/>
<liferay-ui:search-container-column-text
title="Position"
property="position"
/>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
</aui:form>
contact_search_form.jsp:
<%# include file="/html/addressbookportlet/init.jsp" %>
<%
the
ABContactDisplayTerms displayTerms = (ABContactDisplayTerms)searchContainer.getDisplayTerms();
List<ABSociety> societyList = ABSocietyLocalServiceUtil.getABSocieties(0, Integer.MAX_VALUE);
List<ABBrand> brandList = ABBrandLocalServiceUtil.getABBrands(0, Integer.MAX_VALUE);
List<ABContactType> contactTypeList = ABContactTypeLocalServiceUtil.getABContactTypes(0, Integer.MAX_VALUE);
List<ABChannel> channelList = ABChannelLocalServiceUtil.getABChannels(0, Integer.MAX_VALUE);
%>
<liferay-ui:search-toggle
id="toggle_id_contact_search"
displayTerms="<%= displayTerms %>"
buttonLabel="search-contact"
>
<aui:fieldset>
<aui:input name="<%= ABContactDisplayTerms.SURNAME %>" size="20" value="<%= displayTerms.getSurname() %>" />
<aui:input name="<%= ABContactDisplayTerms.NAME %>" size="20" value="<%= displayTerms.getName() %>" />
<aui:input name="<%= ABContactDisplayTerms.POSITION %>" size="20" value="<%= displayTerms.getPosition() %>" />
<aui:input name="<%= ABContactDisplayTerms.DETAIL_VALUE %>" size="20" value="<%= displayTerms.getDetailValue() %>" />
</aui:fieldset>
</liferay-ui:search-toggle>
<c:if test="<%= windowState.equals(WindowState.MAXIMIZED) %>">
<aui:script>
Liferay.Util.focusFormField(document.<portlet:namespace />fm.<portlet:namespace /><%= ABContactDisplayTerms.SURNAME %>);
Liferay.Util.focusFormField(document.<portlet:namespace />fm.<portlet:namespace /><%= ABContactDisplayTerms.KEYWORDS %>);
</aui:script>
</c:if>meDisplay.setIncludeServiceJs(true);
ABContactSearch searchContainer = (ABContactSearch)request.getAttribute("liferay-ui:search:searchContainer");
ABContactDisplayTerm.java:
public class ABContactDisplayTerms extends DisplayTerms {
public static final String NAME = "name";
public static final String SURNAME = "surname";
public static final String POSITION = "position";
public static final String SOCIETY_ID = "societyId";
public static final String CONTACT_TYPE_ID = "contactTypeId";
public static final String BRAND_ID = "brandId";
public static final String CHANNEL_ID = "channelId";
public static final String DETAIL_VALUE = "detailValue";
protected String name;
protected String surname;
protected String position;
protected Long societyId;
protected Long contactTypeId;
protected Long brandId;
protected Long channelId;
protected String detailValue;
public ABContactDisplayTerms(PortletRequest portletRequest) {
super(portletRequest);
name = ParamUtil.getString(portletRequest, NAME);
surname = ParamUtil.getString(portletRequest, SURNAME);
position = ParamUtil.getString(portletRequest, POSITION);
societyId = ParamUtil.getLong(portletRequest, SOCIETY_ID);
contactTypeId = ParamUtil.getLong(portletRequest, CONTACT_TYPE_ID);
brandId = ParamUtil.getLong(portletRequest, BRAND_ID);
channelId = ParamUtil.getLong(portletRequest, CHANNEL_ID);
detailValue = ParamUtil.getString(portletRequest, DETAIL_VALUE);
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getPosition() {
return position;
}
public Long getSocietyId() {
return societyId;
}
public Long getContactTypeId() {
return contactTypeId;
}
public Long getBrandId() {
return brandId;
}
public Long getChannelId() {
return channelId;
}
public String getDetailValue() {
return detailValue;
}
}
and finally ABContactSearch.java
public class ABContactSearch extends SearchContainer<ABContact> {
private static Log _log = LogFactoryUtil.getLog(ABContactSearch.class);
static List<String> headerNames = new ArrayList<String>();
static Map<String, String> orderableHeaders = new HashMap<String, String>();
static {
headerNames.add("name");
headerNames.add("surname");
headerNames.add("position");
headerNames.add("society");
headerNames.add("contact-type");
headerNames.add("channel");
headerNames.add("brand");
headerNames.add("detail-value");
orderableHeaders.put("name", "name");
orderableHeaders.put("surname", "surname");
orderableHeaders.put("society", "society");
orderableHeaders.put("contact-type", "contact-type");
}
public static final String EMPTY_RESULTS_MESSAGE = "no-contacts-were-found";
public ABContactSearch(PortletRequest portletRequest, PortletURL iteratorURL) {
super(
portletRequest, new ABContactDisplayTerms(portletRequest),
new ABContactSearchTerms(portletRequest), DEFAULT_CUR_PARAM,
DEFAULT_DELTA, iteratorURL, headerNames, EMPTY_RESULTS_MESSAGE);
ABContactDisplayTerms displayTerms = (ABContactDisplayTerms)getDisplayTerms();
iteratorURL.setParameter(
ABContactDisplayTerms.NAME, displayTerms.getName());
iteratorURL.setParameter(
ABContactDisplayTerms.SURNAME, displayTerms.getSurname());
iteratorURL.setParameter(
ABContactDisplayTerms.POSITION, displayTerms.getPosition());
iteratorURL.setParameter(
ABContactDisplayTerms.DETAIL_VALUE, displayTerms.getDetailValue());
iteratorURL.setParameter(
ABContactDisplayTerms.SOCIETY_ID, String.valueOf(displayTerms.getSocietyId()));
iteratorURL.setParameter(
ABContactDisplayTerms.CONTACT_TYPE_ID, String.valueOf(displayTerms.getContactTypeId()));
iteratorURL.setParameter(
ABContactDisplayTerms.BRAND_ID, String.valueOf(displayTerms.getBrandId()));
iteratorURL.setParameter(
ABContactDisplayTerms.CHANNEL_ID, String.valueOf(displayTerms.getChannelId()));
try {
String orderByCol = ParamUtil.getString(
portletRequest, "orderByCol", "surname");
String orderByType = ParamUtil.getString(
portletRequest, "orderByType", "asc");
// OrderByComparator orderByComparator =
// UsersAdminUtil.getUserOrderByComparator(
// orderByCol, orderByType);
setOrderableHeaders(orderableHeaders);
setOrderByCol(orderByCol);
setOrderByType(orderByType);
// setOrderByComparator(orderByComparator);
}
catch (Exception e) {
_log.error(e.getMessage());
_log.debug(e.getMessage(), e);
}
}
}
the search container itself is working good, as the base search is performed by default with empty string, but the "search form" is not showing.
I've tryed to put some debug messages on contact_search_form.jsp but none of them are printed into console. It seems the file is not being found or processed by the taglib..
Any help would be appreciated!
My 100% work example, where using liferay-ui: search-container, liferay-ui: search-form and liferay-ui: search-toggle:
My 100% work example, where using liferay-ui: search-container, liferay-ui: search-form and liferay-ui: search-toggle:
view.jsp:
<%# include file="/init.jsp" %>
<%
PortletURL portletURL = renderResponse.createRenderURL();
portletURL.setParameter("mvcPath", "/html/view.jsp");
pageContext.setAttribute("portletURL", portletURL);
%>
<aui:form name="searchForm" action="<%= portletURL.toString() %>" method="post">
<liferay-ui:search-container searchContainer="<%= new UserSearch(renderRequest, portletURL) %>" >
<aui:input disabled="<%= true %>" name="usersRedirect" type="hidden" value="<%= portletURL.toString() %>" />
<%
UserSearchTerms searchTerms = (UserSearchTerms)searchContainer.getSearchTerms();
UserDisplayTerms displayTerms = (UserDisplayTerms)searchContainer.getDisplayTerms();
long organizationId = searchTerms.getOrganizationId();
long userGroupId = searchTerms.getUserGroupId();
Organization organization = null;
if (organizationId > 0) {
try {
organization = OrganizationLocalServiceUtil.getOrganization(organizationId);
}
catch (NoSuchOrganizationException nsoe) {
}
}
UserGroup userGroup = null;
if (userGroupId > 0) {
try {
userGroup = UserGroupLocalServiceUtil.getUserGroup(userGroupId);
}
catch (NoSuchUserGroupException nsuge) {
}
}
%>
<c:if test="<%= organization != null %>">
<aui:input name="<%= UserDisplayTerms.ORGANIZATION_ID %>" type="hidden" value="<%= organization.getOrganizationId() %>" />
<h3><%= HtmlUtil.escape(LanguageUtil.format(pageContext, "users-of-x", organization.getName())) %></h3>
</c:if>
<c:if test="<%= userGroup != null %>">
<aui:input name="<%= UserDisplayTerms.USER_GROUP_ID %>" type="hidden" value="<%= userGroup.getUserGroupId() %>" />
<h3><%= LanguageUtil.format(pageContext, "users-of-x", HtmlUtil.escape(userGroup.getName())) %></h3>
</c:if>
<liferay-ui:search-form
page="/html/user_search.jsp"
searchContainer="<%= searchContainer %>"
servletContext="<%= this.getServletConfig().getServletContext() %>"
/>
<%
LinkedHashMap userParams = new LinkedHashMap();
if (organizationId > 0) {
userParams.put("usersOrgs", new Long(organizationId));
}
if (userGroupId > 0) {
userParams.put("usersUserGroups", new Long(userGroupId));
}
%>
<liferay-ui:search-container-results>
<c:choose>
<c:when test="<%= GetterUtil.getBoolean(PropsUtil.get(PropsKeys.USERS_INDEXER_ENABLED)) && GetterUtil.getBoolean(PropsUtil.get(PropsKeys.USERS_SEARCH_WITH_INDEX)) %>">
<%# include file="/html/user_search_results_index.jspf" %>
</c:when>
<c:otherwise>
<%# include file="/html/user_search_results_database.jspf" %>
</c:otherwise>
</c:choose>
</liferay-ui:search-container-results>
<liferay-ui:search-container-row
className="com.liferay.portal.model.User"
escapedModel="<%= true %>"
keyProperty="userId"
modelVar="curUser"
rowIdProperty="screenName"
>
<liferay-portlet:renderURL varImpl="rowURL" windowState="<%= WindowState.MAXIMIZED.toString() %>">
<portlet:param name="mvcPath" value="/html/user_display.jsp" />
<portlet:param name="redirect" value="<%= searchContainer.getIteratorURL().toString() %>" />
<portlet:param name="userId" value="<%= String.valueOf(curUser.getUserId()) %>" />
</liferay-portlet:renderURL>
<%# include file="/html/search_columns.jspf" %>
</liferay-ui:search-container-row>
<c:if test="<%= (organization != null) || (userGroup != null) %>">
<br />
</c:if>
<c:if test="<%= organization != null %>">
<aui:input name="<%= UserDisplayTerms.ORGANIZATION_ID %>" type="hidden" value="<%= organization.getOrganizationId() %>" />
<liferay-ui:message key="filter-by-organization" />: <%= HtmlUtil.escape(organization.getName()) %><br />
</c:if>
<c:if test="<%= userGroup != null %>">
<aui:input name="<%= UserDisplayTerms.USER_GROUP_ID %>" type="hidden" value="<%= userGroup.getUserGroupId() %>" />
<liferay-ui:message key="filter-by-user-group" />: <%= HtmlUtil.escape(userGroup.getName()) %><br />
</c:if>
<div class="separator"><!-- --></div>
<liferay-ui:search-iterator />
</liferay-ui:search-container>
</aui:form>
user_search.jsp:
<%# include file="/init.jsp" %>
<%
UserSearch searchContainer = (UserSearch)request.getAttribute("liferay-ui:search:searchContainer");
UserDisplayTerms displayTerms = (UserDisplayTerms)searchContainer.getDisplayTerms();
%>
<liferay-ui:search-toggle
buttonLabel="search"
displayTerms="<%= displayTerms %>"
id="toggle_id_user_search"
>
<aui:fieldset>
<aui:input name="<%= displayTerms.FIRST_NAME %>" size="20" type="text" value="<%= displayTerms.getFirstName() %>" />
<aui:input name="<%= displayTerms.MIDDLE_NAME %>" size="20" type="text" value="<%= displayTerms.getMiddleName() %>" />
<aui:input name="<%= displayTerms.LAST_NAME %>" size="20" type="text" value="<%= displayTerms.getLastName() %>" />
<aui:input name="<%= displayTerms.SCREEN_NAME %>" size="20" type="text" value="<%= displayTerms.getScreenName() %>" />
<aui:input name="<%= displayTerms.EMAIL_ADDRESS %>" size="20" type="text" value="<%= displayTerms.getEmailAddress() %>" />
</aui:fieldset>
</liferay-ui:search-toggle>
user_search_results_index.jspf:
<%# page import="com.liferay.portal.kernel.search.Hits" %>
<%# page import="com.liferay.portal.kernel.search.Sort" %>
<%# page import="com.liferay.portal.kernel.search.SortFactoryUtil" %>
<%# page import="com.liferay.portlet.usersadmin.util.UsersAdminUtil" %>
<%
userParams.put("expandoAttributes", searchTerms.getKeywords());
Sort sort = SortFactoryUtil.getSort(User.class, searchContainer.getOrderByCol(), searchContainer.getOrderByType());
while (true) {
Hits hits = null;
if (searchTerms.isAdvancedSearch()) {
hits = UserLocalServiceUtil.search(company.getCompanyId(), searchTerms.getFirstName(), searchTerms.getMiddleName(), searchTerms.getLastName(), searchTerms.getScreenName(), searchTerms.getEmailAddress(), searchTerms.getStatus(), userParams, searchTerms.isAndOperator(), searchContainer.getStart(), searchContainer.getEnd(), sort);
}
else {
hits = UserLocalServiceUtil.search(company.getCompanyId(), searchTerms.getKeywords(), searchTerms.getStatus(), userParams, searchContainer.getStart(), searchContainer.getEnd(), sort);
}
Tuple tuple = UsersAdminUtil.getUsers(hits);
boolean corruptIndex = (Boolean)tuple.getObject(1);
if (!corruptIndex) {
results = (List<User>)tuple.getObject(0);
total = hits.getLength();
break;
}
}
pageContext.setAttribute("results", results);
pageContext.setAttribute("total", total);
%>
user_search_results_database.jspf:
<%
if (searchTerms.isAdvancedSearch()) {
results = UserLocalServiceUtil.search(company.getCompanyId(), searchTerms.getFirstName(), searchTerms.getMiddleName(), searchTerms.getLastName(), searchTerms.getScreenName(), searchTerms.getEmailAddress(), searchTerms.getStatus(), userParams, searchTerms.isAndOperator(), searchContainer.getStart(), searchContainer.getEnd(), searchContainer.getOrderByComparator());
total = UserLocalServiceUtil.searchCount(company.getCompanyId(), searchTerms.getFirstName(), searchTerms.getMiddleName(), searchTerms.getLastName(), searchTerms.getScreenName(), searchTerms.getEmailAddress(), searchTerms.getStatus(), userParams, searchTerms.isAndOperator());
}
else {
results = UserLocalServiceUtil.search(company.getCompanyId(), searchTerms.getKeywords(), searchTerms.getStatus(), userParams, searchContainer.getStart(), searchContainer.getEnd(), searchContainer.getOrderByComparator());
total = UserLocalServiceUtil.searchCount(company.getCompanyId(), searchTerms.getKeywords(), searchTerms.getStatus(), userParams);
}
pageContext.setAttribute("results", results);
pageContext.setAttribute("total", total);
%>
user_display.jsp:
<%# include file="/init.jsp" %>
<%
String backURL = ParamUtil.getString(request, "redirect");
portletDisplay.setURLBack(backURL);
long userId = ParamUtil.getLong(request, "userId");
%>
<liferay-ui:user-display
displayStyle="<%= 2 %>"
userId="<%= userId %>"
/>
search_columns.jspf:
<liferay-ui:search-container-column-text
href="<%= rowURL %>"
name="first-name"
orderable="<%= true %>"
property="firstName"
/>
<liferay-ui:search-container-column-text
href="<%= rowURL %>"
name="last-name"
orderable="<%= true %>"
property="lastName"
/>
<liferay-ui:search-container-column-text
href="<%= rowURL %>"
name="screen-name"
orderable="<%= true %>"
property="screenName"
/>
<liferay-ui:search-container-column-text
href="<%= rowURL %>"
name="organizations"
>
<liferay-ui:write bean="<%= curUser %>" property="organizations" />
</liferay-ui:search-container-column-text>
UserSearch.java:
package kz.b2e.kudos.portal.searchuser.search;
import com.liferay.portal.kernel.dao.search.SearchContainer;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.JavaConstants;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.workflow.WorkflowConstants;
import com.liferay.portal.model.User;
import com.liferay.portal.util.PortletKeys;
import com.liferay.portlet.PortalPreferences;
import com.liferay.portlet.PortletPreferencesFactoryUtil;
import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.portlet.PortletConfig;
import javax.portlet.PortletRequest;
import javax.portlet.PortletURL;
public class UserSearch extends SearchContainer<User> {
static List<String> headerNames = new ArrayList<String>();
static Map<String, String> orderableHeaders = new HashMap<String, String>();
static {
headerNames.add("first-name");
headerNames.add("last-name");
headerNames.add("screen-name");
//headerNames.add("email-address");
headerNames.add("job-title");
headerNames.add("organizations");
orderableHeaders.put("first-name", "first-name");
orderableHeaders.put("last-name", "last-name");
orderableHeaders.put("screen-name", "screen-name");
//orderableHeaders.put("email-address", "email-address");
orderableHeaders.put("job-title", "job-title");
}
public static final String EMPTY_RESULTS_MESSAGE = "no-users-were-found";
public UserSearch(PortletRequest portletRequest, PortletURL iteratorURL) {
this(portletRequest, DEFAULT_CUR_PARAM, iteratorURL);
}
public UserSearch(
PortletRequest portletRequest, String curParam,
PortletURL iteratorURL) {
super(
portletRequest, new UserDisplayTerms(portletRequest),
new UserSearchTerms(portletRequest), curParam, DEFAULT_DELTA,
iteratorURL, headerNames, EMPTY_RESULTS_MESSAGE);
PortletConfig portletConfig =
(PortletConfig)portletRequest.getAttribute(
JavaConstants.JAVAX_PORTLET_CONFIG);
UserDisplayTerms displayTerms = (UserDisplayTerms)getDisplayTerms();
UserSearchTerms searchTerms = (UserSearchTerms)getSearchTerms();
String portletName = portletConfig.getPortletName();
if (!portletName.equals(PortletKeys.USERS_ADMIN)) {
displayTerms.setStatus(WorkflowConstants.STATUS_APPROVED);
searchTerms.setStatus(WorkflowConstants.STATUS_APPROVED);
}
iteratorURL.setParameter(
UserDisplayTerms.STATUS, String.valueOf(displayTerms.getStatus()));
iteratorURL.setParameter(
UserDisplayTerms.EMAIL_ADDRESS, displayTerms.getEmailAddress());
iteratorURL.setParameter(
UserDisplayTerms.FIRST_NAME, displayTerms.getFirstName());
iteratorURL.setParameter(
UserDisplayTerms.LAST_NAME, displayTerms.getLastName());
iteratorURL.setParameter(
UserDisplayTerms.MIDDLE_NAME, displayTerms.getMiddleName());
iteratorURL.setParameter(
UserDisplayTerms.ORGANIZATION_ID,
String.valueOf(displayTerms.getOrganizationId()));
iteratorURL.setParameter(
UserDisplayTerms.ROLE_ID, String.valueOf(displayTerms.getRoleId()));
iteratorURL.setParameter(
UserDisplayTerms.SCREEN_NAME, displayTerms.getScreenName());
iteratorURL.setParameter(
UserDisplayTerms.USER_GROUP_ID,
String.valueOf(displayTerms.getUserGroupId()));
try {
PortalPreferences preferences =
PortletPreferencesFactoryUtil.getPortalPreferences(
portletRequest);
String orderByCol = ParamUtil.getString(
portletRequest, "orderByCol");
String orderByType = ParamUtil.getString(
portletRequest, "orderByType");
if (Validator.isNotNull(orderByCol) &&
Validator.isNotNull(orderByType)) {
preferences.setValue(
PortletKeys.USERS_ADMIN, "users-order-by-col", orderByCol);
preferences.setValue(
PortletKeys.USERS_ADMIN, "users-order-by-type",
orderByType);
}
else {
orderByCol = preferences.getValue(
PortletKeys.USERS_ADMIN, "users-order-by-col", "last-name");
orderByType = preferences.getValue(
PortletKeys.USERS_ADMIN, "users-order-by-type", "asc");
}
OrderByComparator orderByComparator =
UsersAdminUtil.getUserOrderByComparator(
orderByCol, orderByType);
setOrderableHeaders(orderableHeaders);
setOrderByCol(orderByCol);
setOrderByType(orderByType);
setOrderByComparator(orderByComparator);
}
catch (Exception e) {
_log.error(e);
}
}
private static Log _log = LogFactoryUtil.getLog(UserSearch.class);
}
UserSearchTerms.java:
package kz.b2e.kudos.portal.searchuser.search;
import com.liferay.portal.kernel.dao.search.SearchContainer;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.JavaConstants;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.workflow.WorkflowConstants;
import com.liferay.portal.model.User;
import com.liferay.portal.util.PortletKeys;
import com.liferay.portlet.PortalPreferences;
import com.liferay.portlet.PortletPreferencesFactoryUtil;
import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.portlet.PortletConfig;
import javax.portlet.PortletRequest;
import javax.portlet.PortletURL;
public class UserSearch extends SearchContainer<User> {
static List<String> headerNames = new ArrayList<String>();
static Map<String, String> orderableHeaders = new HashMap<String, String>();
static {
headerNames.add("first-name");
headerNames.add("last-name");
headerNames.add("screen-name");
//headerNames.add("email-address");
headerNames.add("job-title");
headerNames.add("organizations");
orderableHeaders.put("first-name", "first-name");
orderableHeaders.put("last-name", "last-name");
orderableHeaders.put("screen-name", "screen-name");
//orderableHeaders.put("email-address", "email-address");
orderableHeaders.put("job-title", "job-title");
}
public static final String EMPTY_RESULTS_MESSAGE = "no-users-were-found";
public UserSearch(PortletRequest portletRequest, PortletURL iteratorURL) {
this(portletRequest, DEFAULT_CUR_PARAM, iteratorURL);
}
public UserSearch(
PortletRequest portletRequest, String curParam,
PortletURL iteratorURL) {
super(
portletRequest, new UserDisplayTerms(portletRequest),
new UserSearchTerms(portletRequest), curParam, DEFAULT_DELTA,
iteratorURL, headerNames, EMPTY_RESULTS_MESSAGE);
PortletConfig portletConfig =
(PortletConfig)portletRequest.getAttribute(
JavaConstants.JAVAX_PORTLET_CONFIG);
UserDisplayTerms displayTerms = (UserDisplayTerms)getDisplayTerms();
UserSearchTerms searchTerms = (UserSearchTerms)getSearchTerms();
String portletName = portletConfig.getPortletName();
if (!portletName.equals(PortletKeys.USERS_ADMIN)) {
displayTerms.setStatus(WorkflowConstants.STATUS_APPROVED);
searchTerms.setStatus(WorkflowConstants.STATUS_APPROVED);
}
iteratorURL.setParameter(
UserDisplayTerms.STATUS, String.valueOf(displayTerms.getStatus()));
iteratorURL.setParameter(
UserDisplayTerms.EMAIL_ADDRESS, displayTerms.getEmailAddress());
iteratorURL.setParameter(
UserDisplayTerms.FIRST_NAME, displayTerms.getFirstName());
iteratorURL.setParameter(
UserDisplayTerms.LAST_NAME, displayTerms.getLastName());
iteratorURL.setParameter(
UserDisplayTerms.MIDDLE_NAME, displayTerms.getMiddleName());
iteratorURL.setParameter(
UserDisplayTerms.ORGANIZATION_ID,
String.valueOf(displayTerms.getOrganizationId()));
iteratorURL.setParameter(
UserDisplayTerms.ROLE_ID, String.valueOf(displayTerms.getRoleId()));
iteratorURL.setParameter(
UserDisplayTerms.SCREEN_NAME, displayTerms.getScreenName());
iteratorURL.setParameter(
UserDisplayTerms.USER_GROUP_ID,
String.valueOf(displayTerms.getUserGroupId()));
try {
PortalPreferences preferences =
PortletPreferencesFactoryUtil.getPortalPreferences(
portletRequest);
String orderByCol = ParamUtil.getString(
portletRequest, "orderByCol");
String orderByType = ParamUtil.getString(
portletRequest, "orderByType");
if (Validator.isNotNull(orderByCol) &&
Validator.isNotNull(orderByType)) {
preferences.setValue(
PortletKeys.USERS_ADMIN, "users-order-by-col", orderByCol);
preferences.setValue(
PortletKeys.USERS_ADMIN, "users-order-by-type",
orderByType);
}
else {
orderByCol = preferences.getValue(
PortletKeys.USERS_ADMIN, "users-order-by-col", "last-name");
orderByType = preferences.getValue(
PortletKeys.USERS_ADMIN, "users-order-by-type", "asc");
}
OrderByComparator orderByComparator =
UsersAdminUtil.getUserOrderByComparator(
orderByCol, orderByType);
setOrderableHeaders(orderableHeaders);
setOrderByCol(orderByCol);
setOrderByType(orderByType);
setOrderByComparator(orderByComparator);
}
catch (Exception e) {
_log.error(e);
}
}
private static Log _log = LogFactoryUtil.getLog(UserSearch.class);
}
UserDisplayTerms.java
package kz.b2e.kudos.portal.searchuser.search;
import com.liferay.portal.kernel.dao.search.DisplayTerms;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.workflow.WorkflowConstants;
import javax.portlet.PortletRequest;
public class UserDisplayTerms extends DisplayTerms {
public static final String EMAIL_ADDRESS = "emailAddress";
public static final String FIRST_NAME = "firstName";
public static final String LAST_NAME = "lastName";
public static final String MIDDLE_NAME = "middleName";
public static final String ORGANIZATION_ID = "organizationId";
public static final String ROLE_ID = "roleId";
public static final String SCREEN_NAME = "screenName";
public static final String STATUS = "status";
public static final String USER_GROUP_ID = "userGroupId";
public UserDisplayTerms(PortletRequest portletRequest) {
super(portletRequest);
String statusString = ParamUtil.getString(portletRequest, STATUS);
if (Validator.isNotNull(statusString)) {
status = GetterUtil.getInteger(statusString);
}
emailAddress = ParamUtil.getString(portletRequest, EMAIL_ADDRESS);
firstName = ParamUtil.getString(portletRequest, FIRST_NAME);
lastName = ParamUtil.getString(portletRequest, LAST_NAME);
middleName = ParamUtil.getString(portletRequest, MIDDLE_NAME);
organizationId = ParamUtil.getLong(portletRequest, ORGANIZATION_ID);
roleId = ParamUtil.getLong(portletRequest, ROLE_ID);
screenName = ParamUtil.getString(portletRequest, SCREEN_NAME);
userGroupId = ParamUtil.getLong(portletRequest, USER_GROUP_ID);
}
public String getEmailAddress() {
return emailAddress;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getMiddleName() {
return middleName;
}
public long getOrganizationId() {
return organizationId;
}
public long getRoleId() {
return roleId;
}
public String getScreenName() {
return screenName;
}
public int getStatus() {
return status;
}
public long getUserGroupId() {
return userGroupId;
}
public boolean isActive() {
if (status == WorkflowConstants.STATUS_APPROVED) {
return true;
}
else {
return false;
}
}
public void setStatus(int status) {
this.status = status;
}
protected String emailAddress;
protected String firstName;
protected String lastName;
protected String middleName;
protected long organizationId;
protected long roleId;
protected String screenName;
protected int status;
protected long userGroupId;
}
Put your code inside
<aui:form action="<%= portletURL.toString() %>" method="post" name="yourForm">
</aui:form>
Related
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); }
p:media component content not update
I am using primefaces p:media component to display pdf into my application.When user click on commandButton in view ; I proceed somme task in my managedBean bean to change pdf content ; but I notice that despite of fact that my managedBean method is called and differents values change , My p:media component not updated. What is the problem?? <h:form id="statistiques" prependId="false"> <h3 class="row header smaller lighter blue"> <span class="col-xs-6"> Statistiques </span><!-- /.col --> </h3> <div class="row statistique-form"> <div class="form-group col-sm-2"> <label class="control-label col-xs-12 col-sm-12" for="date-naissance">PĂ©riode</label> <div class="col-xs-12 col-sm-12"> <div class="input-group"> <input class="form-control" type="text" name="date-range-picker" id="id-date-range-picker-1" jsf:value="#{statistiqueOneBean.periode}"/> </div> </div> </div> <div class="form-group col-sm-2"> <label class="control-label col-xs-12 col-sm-12"></label> <div class="col-xs-12 col-sm-12"> <div class="btn-toolbar btn-opt"> <p:commandButton action="#{statistiqueOneBean.create}" ajax="false" value="Visualiser" id="submit" immediate="true" class="btn btn-warning dropdown-toggle btn-opt-btn" > </p:commandButton> </div> </div> </div> <div class="form-group col-sm-2"> <label class="control-label col-xs-12 col-sm-12"></label> <div class="col-xs-12 col-sm-12"> <div class="btn-toolbar btn-opt"> <p:commandButton id="downloadLinkPdf" ajax="true" immediate="true" value="Download to pdf" class="btn btn-warning dropdown-toggle btn-opt-btn" > <p:fileDownload value ="#{statistiqueOneBean.pdf}" /> </p:commandButton> </div> </div> </div> <div class="form-group col-sm-2"> <label class="control-label col-xs-12 col-sm-12"></label> <div class="col-xs-12 col-sm-12"> <div class="btn-toolbar btn-opt"> <p:commandButton id="downloadLinkWord" ajax="false" immediate="true" value="Download to word" class="btn btn-warning dropdown-toggle btn-opt-btn" > <p:fileDownload value ="#{statistiqueOneBean.doc}" /> </p:commandButton> </div> </div> </div> <div class="form-group col-sm-2"> <label class="control-label col-xs-12 col-sm-12"></label> <div class="col-xs-12 col-sm-12"> <div class="btn-toolbar btn-opt"> <p:commandButton id="downloadLinkExcel" ajax="false" immediate="true" value="Download to excel" class="btn btn-warning dropdown-toggle btn-opt-btn" > <p:fileDownload value ="#{statistiqueOneBean.xls}"/> </p:commandButton> </div> </div> </div> </div> <hr></hr> <div class="row"> <div class="panel-group"> <div class="col-md-12 center"> <p:media id="apercu" value="#{statistiqueOneBean.apercu}" player="pdf" width="1024" height="500"> </p:media> </div> </div> </div> </h:form> this is my view code source #Named(value = "statistiqueOneBean") #SessionScoped public class StatistiqueOneBean implements Serializable { private JasperPrint jasperPrint; private String startDate = "2015-01-01"; private String endDate = "2015-08-25"; private String periode; private StreamedContent doc; private StreamedContent xls; private StreamedContent pdf; #Inject StatistiqueFacade statistiqueFacade; public StatistiqueOneBean() { } #PostConstruct public void init() { } public JasperPrint getJasperPrint() { return jasperPrint; } public void setJasperPrint(JasperPrint jasperPrint) { this.jasperPrint = jasperPrint; } public StreamedContent getApercu() { String reportPath = "/Users/administrateur/NetBeansProjects/juridictionOne.jasper"; StreamedContent apercu = null; try { HashMap parameterMap = new HashMap(); parameterMap.put("dossier_enrol", "2"); parameterMap.put("dossier_traite", "5"); parameterMap.put("duree_moy", "2"); jasperPrint = JasperFillManager.fillReport(reportPath, parameterMap, createReportDataSource(startDate, endDate)); apercu = Reporter.PDFStreamedContent(jasperPrint); System.out.println(apercu.getStream()); return apercu; } catch (JRException ex) { Logger.getLogger(StatistiqueOneBean.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(StatistiqueOneBean.class.getName()).log(Level.SEVERE, null, ex); } return apercu; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public String getPeriode() { return periode; } public void setPeriode(String periode) { this.periode = periode; } public void create() throws IOException, JRException { FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("statistiqueOneBean", null); System.out.println("change"); System.out.println("change " + RequestListener.periode); startDate = "2015-01-01"; endDate = "2015-01-01"; } private JRDataSource createReportDataSource(String startDate, String endDate) { JRBeanCollectionDataSource datasource = new JRBeanCollectionDataSource(statistiqueFacade.statistiqueOne(startDate, endDate)); /*JRBeanArrayDataSource datasource; JuridictionStatistiqueOne[] reportRows = initializeBeanArray(); datasource = new JRBeanArrayDataSource(reportRows);*/ return datasource; } public void doDocx() throws IOException { String reportPath = "/Users/administrateur/NetBeansProjects/juridictionOne.jasper"; try { jasperPrint = JasperFillManager.fillReport(reportPath, new HashMap(), createReportDataSource("2015-01-01", "2015-08-25")); doc = Reporter.DocStreamedContent(jasperPrint); } catch (JRException ex) { Logger.getLogger(StatistiqueOneBean.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(StatistiqueOneBean.class.getName()).log(Level.SEVERE, null, ex); } } private JuridictionStatistiqueOne[] initializeBeanArray() { JuridictionStatistiqueOne[] reportRows = new JuridictionStatistiqueOne[4]; reportRows[0] = new JuridictionStatistiqueOne("N263Y", "1", "1", "1", "1", "1"); reportRows[1] = new JuridictionStatistiqueOne("N263Y", "1", "1", "1", "1", "1"); reportRows[2] = new JuridictionStatistiqueOne("N263Y", "1", "1", "1", "1", "1"); reportRows[3] = new JuridictionStatistiqueOne("N263Y", "1", "1", "1", "1", "1"); return reportRows; } public void getPDF(String startDate, String endDate) throws IOException { StreamedContent apercu = null; String reportPath = "/Users/administrateur/NetBeansProjects/juridictionOne.jasper"; try { HashMap parameterMap = new HashMap(); parameterMap.put("dossier_enrol", "2"); parameterMap.put("dossier_traite", "2"); parameterMap.put("duree_moy", "2"); jasperPrint = JasperFillManager.fillReport(reportPath, parameterMap, createReportDataSource(startDate, endDate)); apercu = Reporter.PDFStreamedContent(jasperPrint); } catch (JRException ex) { Logger.getLogger(StatistiqueOneBean.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(StatistiqueOneBean.class.getName()).log(Level.SEVERE, null, ex); } } public void doPDF(String startDate, String endDate) throws IOException { getPDF(startDate, endDate); } public StreamedContent getDoc() { String reportPath = "/Users/administrateur/NetBeansProjects/juridictionOne.jasper"; try { jasperPrint = JasperFillManager.fillReport(reportPath, new HashMap(), createReportDataSource("2015-01-01", "2015-08-25")); doc = Reporter.DocStreamedContent(jasperPrint); } catch (JRException ex) { Logger.getLogger(StatistiqueOneBean.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(StatistiqueOneBean.class.getName()).log(Level.SEVERE, null, ex); } return doc; } public StreamedContent getPdf() { String reportPath = "/Users/administrateur/NetBeansProjects/juridictionOne.jasper"; try { jasperPrint = JasperFillManager.fillReport(reportPath, new HashMap(), createReportDataSource("2015-01-01", "2015-08-25")); pdf = Reporter.PDFStreamedContent(jasperPrint); } catch (JRException ex) { Logger.getLogger(StatistiqueOneBean.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(StatistiqueOneBean.class.getName()).log(Level.SEVERE, null, ex); } return pdf; } public StreamedContent getXls() { String reportPath = "/Users/administrateur/NetBeansProjects/juridictionOne.jasper"; try { jasperPrint = JasperFillManager.fillReport(reportPath, new HashMap(), createReportDataSource("2015-01-01", "2015-08-25")); xls = Reporter.XlsStreamedContent(jasperPrint); } catch (JRException ex) { Logger.getLogger(StatistiqueOneBean.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(StatistiqueOneBean.class.getName()).log(Level.SEVERE, null, ex); } return xls; } } This is my managed bean code source
Not able to call managed bean method on submit button
Here is my code of my .xhtml page <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" template="/WEB-INF/templates/admin/main_body_template.xhtml"> <ui:define name="bodycontent"> <h:panelGroup> <h:form class="form-horizontal" enctype="multipart/form-data"> <!-- Build page from here: Usual with <div class="row-fluid"></div> --> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default" style="min-height: inherit;"> <div class="panel-heading"> <h4><span class="icon16 icomoon-icon-pencil-3"></span><span>Create New Module</span></h4> </div> <div class="panel-body"> <div class="form-group"> <label class="col-lg-5 control-label" for="select">Select app</label> <div class="col-lg-3 dropdown-error"> <h:selectOneMenu class="form-control" required="required" value="#{moduleBean.appList}"> <f:selectItem itemValue="0" itemLabel="-- Please select app --"></f:selectItem> <f:selectItem itemValue="1" itemLabel="AdMan"></f:selectItem> <f:selectItem itemValue="2" itemLabel="Neokala"></f:selectItem> <f:selectItem itemValue="3" itemLabel="Recrudesk"></f:selectItem> <f:selectItem itemValue="4" itemLabel="E-commerce"></f:selectItem> <f:selectItem itemValue="5" itemLabel="Restaurants"></f:selectItem> <f:selectItem itemValue="6" itemLabel="Account"></f:selectItem> <f:selectItem itemValue="7" itemLabel="MockExam"></f:selectItem> </h:selectOneMenu> </div> </div> <!-- End .form-group --> <hr/> <div class="form-group a1"> <label class="col-lg-5 control-label" for="normalInput">Module name</label> <div class="col-lg-3"> <h:inputText class="form-control" required="true" value="#{moduleBean.selected.moduleName}"></h:inputText> </div> <a href="#" class="btip" rel="tooltip" data-placement="right" data-original-title="Tooltip on right"> <span class="icon16 entypo-icon-help-2 icon-position"></span> </a> </div> <!-- End .form-group --> <div class="form-group b1"> <label class="col-lg-5 control-label" for="fileinput">Upload image</label> <div class="col-lg-3"> <h:inputFile class="form-control" id="file" value="#{moduleBean.imgFile}"/> </div> <a href="#" class="btip" rel="tooltip" data-placement="right" data-original-title="Tooltip on right"> <span class="icon16 entypo-icon-help-2 icon-position"></span> </a> </div> <!-- End .form-group --> <div class="form-group"> <label class="col-lg-5 control-label" for="checkboxes">Active</label> <div class="col-lg-3"> <div class="normal-toggle-button toggle-custom-size"> <h:selectBooleanCheckbox class="nostyle" value="#{moduleBean.selected.active}"></h:selectBooleanCheckbox> </div> </div> </div> <!-- End .form-group --> <div class="form-group"> <label class="col-lg-5 control-label" for="checkboxes">Add-on</label> <div class="col-lg-3"> <div class="left marginR10"> <div class="normal-toggle-button toggle-custom-size"> <h:selectBooleanCheckbox class="nostyle" value="#{moduleBean.selected.addOn}"></h:selectBooleanCheckbox> </div> </div> </div> </div> <!-- End .form-group --> </div> <div class="panel-heading form-footer-top"> <div class="footer-btn-position"> <h:commandButton class="btn btn-primary nostyle marginR5" value="Save" action="#{moduleBean.create()}"></h:commandButton> <h:commandButton type="button" class="btn btn-warning nostyle cancel-btn-position" value="Cancel"></h:commandButton> </div> <div style="clear:both;"></div> </div> </div> <!-- End .panel --> </div> <!-- End .span12 --> </div> <!-- End .row --> </h:form> </h:panelGroup> </ui:define> </ui:composition> and below is my managedbean code. /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.aptegrainc.ymapps.supadm.managedbeans.masters; import com.aptegrainc.ymapps.supadm.controller.masters.ModuleController; import com.aptegrainc.ymapps.supadm.dto.ModuleVo; import com.aptegrainc.ymapps.supadm.managedbeans.UserDataBean; import static com.aptegrainc.ymapps.supadm.managedbeans.UserDataBean.setErrorMessage; import static com.aptegrainc.ymapps.supadm.managedbeans.UserDataBean.setInfoMessage; import java.io.Serializable; import java.util.List; import java.util.ResourceBundle; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import javax.servlet.http.Part; /** * * #author Vaibhavi */ #ManagedBean(name = "moduleBean") #ViewScoped public class ModuleBean extends UserDataBean implements Serializable{ private static final long serialVersionUID = 1L; private DataModel items; private ModuleVo current; private Part imgFile; private boolean createPanel = false; private ModuleController moduleController = new ModuleController(); private String appList; public Part getImgFile() { return imgFile; } public void setImgFile(Part imgFile) { this.imgFile = imgFile; } public ModuleVo getSelected() { if (current == null) { current = new ModuleVo(); } return current; } /** * Creates a new instance of ModuleBean */ public ModuleBean() { } public String create() { System.out.println("current : " + current); System.out.println("---------"+current.getAppName()+current.getModuleName()+current.isActive()+current.isAddOn()); if(checkError()){ try { System.out.println("---------"+current.getAppName()+current.getModuleName()+current.isActive()+current.isAddOn()); current.setActive(true); boolean val = moduleController.create(current); if(!val){ return "pretty:commonerror"; } else if (val){ setInfoMessage("Module created successfully"); } setCreatePanel(false); recreateModel(); return "success"; } catch (Exception e) { setErrorMessage(ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured")); } } return "fail"; } public boolean checkError(){ boolean flag = true; if(current.getModuleName() == null || current.getModuleName().equals("")){ //setErrorMessage("Enter module name"); flag = false; } return flag; } private void recreateModel() { items = null; } // Getters, Setters /** * #return the items */ public DataModel getItems() { if (items == null) { List<ModuleVo> moduleVos = null; //moduleVos = moduleController.findAll(); items = new ListDataModel(moduleVos); } return items; } /** * #param items the items to set */ public void setItems(DataModel items) { this.items = items; } /** * #return the current */ public ModuleVo getCurrent() { return current; } /** * #param current the current to set */ public void setCurrent(ModuleVo current) { this.current = current; } /** * #return the moduleController */ public ModuleController getModuleController() { return moduleController; } /** * #param moduleController the moduleController to set */ public void setModuleController(ModuleController moduleController) { this.moduleController = moduleController; } /** * #return the appList */ public String getAppList() { return appList; } /** * #param appList the appList to set */ public void setAppList(String appList) { this.appList = appList; } /** * #return the createPanel */ public boolean isCreatePanel() { return createPanel; } /** * #param createPanel the createPanel to set */ public void setCreatePanel(boolean createPanel) { this.createPanel = createPanel; } } I have just called a method on submit button but its not calling even the method. I have checked the code many times but couldn't find any logical error. I am not getting why the bean method is not called.
How to handle invalid authentication in liferay sign in portlet
Im trying to customize the login portlet for my purpose using this portlet login sample. But when i login with test#liferay.com with a wrong password it shows "web page is not available" SignInPortlet.java public class SignInPortlet extends MVCPortlet { #Override public void processAction( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { String className = "com.liferay.portlet.login.action.LoginAction"; PortletConfig portletConfig = getPortletConfig(); NoRedirectActionResponse noRedirectActionResponse = new NoRedirectActionResponse(actionResponse); try { PortletActionInvoker.processAction( className, portletConfig, actionRequest, noRedirectActionResponse); } catch (Exception e) { _log.error(e, e); } String login = ParamUtil.getString(actionRequest, "login"); String password = ParamUtil.getString(actionRequest, "password"); String rememberMe = ParamUtil.getString(actionRequest, "rememberMe"); if (Validator.isNull(noRedirectActionResponse.getRedirectLocation())) { actionResponse.setRenderParameter("login", login); actionResponse.setRenderParameter("rememberMe", rememberMe); } else { String redirect = PortalUtil.getPathMain() + "/portal/login?login=" + login + "&password=" + password + "&rememberMe=" + rememberMe; actionResponse.sendRedirect(redirect); } } private static Log _log = LogFactoryUtil.getLog(SignInPortlet.class); } View.jsp <%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %> <%# taglib uri="http://liferay.com/tld/aui" prefix="aui" %> <%# taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %> <%# taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %> <%# page import="com.liferay.portal.CookieNotSupportedException" %> <%# page import="com.liferay.portal.NoSuchUserException" %> <%# page import="com.liferay.portal.PasswordExpiredException" %> <%# page import="com.liferay.portal.UserEmailAddressException" %> <%# page import="com.liferay.portal.UserLockoutException" %> <%# page import="com.liferay.portal.UserPasswordException" %> <%# page import="com.liferay.portal.UserScreenNameException" %> <%# page import="com.liferay.portal.kernel.language.LanguageUtil" %> <%# page import="com.liferay.portal.kernel.util.ClassResolverUtil" %> <%# page import="com.liferay.portal.kernel.util.Constants" %> <%# page import="com.liferay.portal.kernel.util.GetterUtil" %> <%# page import="com.liferay.portal.kernel.util.HtmlUtil" %> <%# page import="com.liferay.portal.kernel.util.MethodKey" %> <%# page import="com.liferay.portal.kernel.util.ParamUtil" %> <%# page import="com.liferay.portal.kernel.util.PortalClassInvoker" %> <%# page import="com.liferay.portal.kernel.util.PropsUtil" %> <%# page import="com.liferay.portal.model.Company" %> <%# page import="com.liferay.portal.security.auth.AuthException" %> <%# page import="javax.portlet.WindowState" %> <portlet:defineObjects /> <liferay-theme:defineObjects /> <c:choose> <c:when test="<%= themeDisplay.isSignedIn() %>"> <% String signedInAs = user.getFullName(); if (themeDisplay.isShowMyAccountIcon()) { signedInAs = "" + signedInAs + ""; } %> <%= LanguageUtil.format(pageContext, "you-are-signed-in-as-x", signedInAs, false) %> </c:when> <c:otherwise> <% MethodKey methodKey = new MethodKey(ClassResolverUtil.resolveByPortalClassLoader("com.liferay.portlet.login.util.LoginUtil"), "getLogin", HttpServletRequest.class, String.class, Company.class); String login = GetterUtil.getString((String)PortalClassInvoker.invoke(false, methodKey, request, "login", company)); boolean rememberMe = ParamUtil.getBoolean(request, "rememberMe"); %> <portlet:actionURL var="loginURL" /> <aui:form action="<%= loginURL %>" method="post" name="fm"> <aui:input name="saveLastPath" type="hidden" value="<%= false %>" /> <aui:input name="<%= Constants.CMD %>" type="hidden" value="<%= Constants.UPDATE %>" /> <aui:input name="rememberMe" type="hidden" value="<%= rememberMe %>" /> <liferay-ui:error exception="<%= AuthException.class %>" message="authentication-failed" /> <liferay-ui:error exception="<%= CookieNotSupportedException.class %>" message="authentication-failed-please-enable-browser-cookies" /> <liferay-ui:error exception="<%= NoSuchUserException.class %>" message="please-enter-a-valid-login" /> <liferay-ui:error exception="<%= PasswordExpiredException.class %>" message="your-password-has-expired" /> <liferay-ui:error exception="<%= UserEmailAddressException.class %>" message="please-enter-a-valid-login" /> <liferay-ui:error exception="<%= UserLockoutException.class %>" message="this-account-has-been-locked" /> <liferay-ui:error exception="<%= UserPasswordException.class %>" message="please-enter-a-valid-password" /> <liferay-ui:error exception="<%= UserScreenNameException.class %>" message="please-enter-a-valid-screen-name" /> <table class="lfr-table"> <tr> <td> <aui:input name="login" style="width: 120px;" type="text" value="<%= HtmlUtil.escape(login) %>" /> </td> </tr> <tr> <td> <aui:input name="password" style="width: 120px;" type="password" value="" /> <span id="<portlet:namespace />passwordCapsLockSpan" style="display: none;"><liferay-ui:message key="caps-lock-is-on" /></span> </td> </tr> <c:if test='<%= company.isAutoLogin() && !GetterUtil.getBoolean(PropsUtil.get("session.disabled")) %>'> <tr> <td> <aui:input checked="<%= rememberMe %>" name="rememberMe" type="checkbox" /> </td> </tr> </c:if> </table> <br /> <input type="submit" value="<liferay-ui:message key="sign-in" />" /> </aui:form> <c:if test="<%= renderRequest.getWindowState().equals(WindowState.MAXIMIZED) %>"> <aui:script> Liferay.Util.focusFormField(document.<portlet:namespace />fm.<portlet:namespace />login); </aui:script> </c:if> <aui:script use="aui-base"> A.one('#<portlet:namespace />password').on( 'keypress', function(event) { Liferay.Util.showCapsLock(event, '<portlet:namespace />passwordCapsLockSpan'); } ); </aui:script> </c:otherwise> </c:choose> Does any one know how to solve this?
I changed the portlet code like this .Now it is ok public class SignInPortlet extends MVCPortlet { #Override public void processAction( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { String className = "com.liferay.portlet.login.action.LoginAction"; PortletConfig portletConfig = getPortletConfig(); NoRedirectActionResponse noRedirectActionResponse = new NoRedirectActionResponse(actionResponse); try { PortletActionInvoker.processAction( className, portletConfig, actionRequest, noRedirectActionResponse); } catch (Exception e) { _log.error(e, e); } String login = ParamUtil.getString(actionRequest, "login"); String password = ParamUtil.getString(actionRequest, "password"); String rememberMe = ParamUtil.getString(actionRequest, "rememberMe"); Object object = SessionErrors.get( actionRequest, AuthException.class.getName() ); if (( object != null ) || Validator.isNull(noRedirectActionResponse.getRedirectLocation())) { actionResponse.setRenderParameter("login", login); actionResponse.setRenderParameter("rememberMe", rememberMe); } else { String redirect = PortalUtil.getPathMain() + "/portal/login?login=" + login + "&password=" + password + "&rememberMe=" + rememberMe; actionResponse.sendRedirect(redirect); } } private static Log _log = LogFactoryUtil.getLog(SignInPortlet.class); }
Passing parameters to Liferay PortletURL
I would like to validate the request of an user by doing he types his personal key. First of all he does the request, now the portlet redirects to a second jsp file where he validates with the key and finally if it is ok the portlet complete the request otherwise returns to the first step. Here is the code, 1.- view.jsp (the request) <%# include file="/html/blue/init.jsp" %> Welcome to our Colors workflow <br/> <% PortletURL redirectURL = renderResponse.createActionURL(); redirectURL.setParameter(ActionRequest.ACTION_NAME, "redirect"); %> <aui:form name="fmAdd" method="POST" action="<%= redirectURL.toString() %>"> <aui:input type="hidden" name="myaction" value="add" /> <aui:button type="submit" value="Add New Box"/> </aui:form> <aui:form name="fmList" method="POST" action="<%= redirectURL.toString() %>"> <aui:input type="hidden" name="myaction" value="list" /> <aui:button type="submit" value="Show All Boxes"/> </aui:form> 2.- the java code, public void redirect(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { String action = ParamUtil.getString(actionRequest, "myaction"); PortletURL redirectURL = null; String redirectJSP = "/checkuser.jsp"; if(action != null) { String portletName = (String)actionRequest.getAttribute(WebKeys.PORTLET_ID); ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); redirectURL = PortletURLFactoryUtil.create(PortalUtil.getHttpServletRequest(actionRequest), portletName, themeDisplay.getLayout().getPlid(), PortletRequest.RENDER_PHASE); redirectURL.setParameter("myaction", action); redirectURL.setParameter("jspPage", redirectJSP); } actionResponse.sendRedirect(redirectURL.toString()); } 3._ checkuser.jsp (the user validate with his key) <%# include file="/html/blue/init.jsp" %> <% PortletURL checkUserURL = renderResponse.createActionURL(); checkUserURL.setParameter(ActionRequest.ACTION_NAME, "checkUser"); String myaction = renderRequest.getParameter("myaction"); %> <p> Your action: <%= myaction %> </p> <aui:form name="fm" method="POST" action="<%= checkUserURL.toString() %>"> <aui:input type="hidden" name="myaction" value="<%= myaction %>" /> <aui:input type="text" name="key" value=""/> <aui:button type="submit" value="Save"/> </aui:form> In this phase I am getting the first problem because I do not see the value of the request (myaction variable). This is only for debug. 4._ the java code that catches the last form, public void checkUser(ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortletException { String key = ParamUtil.getString(actionRequest, "key"); String action = ParamUtil.getString(actionRequest, "myaction"); String portletName = (String)actionRequest.getAttribute(WebKeys.PORTLET_ID); ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); PortletURL redirectURL = PortletURLFactoryUtil.create(PortalUtil.getHttpServletRequest(actionRequest), portletName, themeDisplay.getLayout().getPlid(), PortletRequest.RENDER_PHASE); String redirectJSP = "/view.jsp"; if(key != null) { if(key.equalsIgnoreCase("blue")) { if(action != null) { if(action.equalsIgnoreCase("add")) { redirectJSP = "/update.jsp"; } if(action.equalsIgnoreCase("list")) { redirectJSP = "/list.jsp"; } } } } redirectURL.setParameter("jspPage", redirectJSP); actionResponse.sendRedirect(redirectURL.toString()); } In this phase the portlet always goes to view.jsp where the user does the request. I am thinking both key and action variables are null or at least one of them. What am I doing wrong? Regards, Jose
In Liferay, the parameters are set with a namespace so that they don't cause problems when there are more than 1 portlet on the page. Especially if you have the exact same portlet on the page twice! So when you're setting myaction, it really gets set to something like _myportlet_INSTANCE_xlka_myaction or something similar. You can use com.liferay.portal.kernel.util.ParamUtil to help you get your parameters without having to worry about the scoping. For example: ParamUtil.getString(request, "myaction");