Tuesday, April 24, 2012

How to create a form in Liferay

You may need to create a form in liferay. As you may be aware that in liferay every page consists of portlets, hence to create a form you need to create a portlet.
Below example shows how to create a form in liferay. In this example we have a view.jsp which contains form fields and the form is submitted to another jsp (i.e. submit.jsp)

To submit the form in liferay you need to create a renderURL as shown below. Please see the self explanatory example below.

view.jsp

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>

<portlet:renderURL var="submitURL">
 <portlet:param name="jspPage" value="/submit.jsp" />
</portlet:renderURL>

<aui:form action="<%= submitURL %>" method="post">

 <aui:input label="First name" name="fName" type="text" value=""/>
 <aui:input label="Last name" name="lName" type="text" value=""/>
 <aui:input label="Password" name="password" type="password" value=""/>

 <b>Gender</b>
 <aui:input label="Male" name="gender" type="radio" value="Male"/>
 <aui:input label="Female" name="gender" type="radio" value="Female"/>

 <b>Language</b>
 <aui:input label="C" name="lang" type="checkbox" value="C"/>
 <aui:input label="Java" name="lang" type="checkbox" value="Java"/>
 <aui:input label="Perl" name="lang" type="checkbox" value="Perl"/>

 <aui:input name="hiddenValue" type="hidden" value="hide it"/>

 <aui:button type="submit" value="Submit Form"/>
 <aui:button type="reset" value="Reset Values"/>

</aui:form>


submit.jsp

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

<portlet:defineObjects />

<%
 String fName = renderRequest.getParameter("fName");
 String lName = renderRequest.getParameter("lName");
 String password = renderRequest.getParameter("password");
 String gender = renderRequest.getParameter("gender");
 String[] lang = renderRequest.getParameterValues("lang");
 String hiddenValue = renderRequest.getParameter("hiddenValue");
%>

<b>Values Submitted</b><br/>

First name - <%= fName %><br/>
Last name - <%= lName %><br/>
Password - <%= password %><br/>
Gender - <%= gender %><br/>
Language - <% for(String l : lang) { %> <%= l %> <% } %><br/>
Hidden - <%= hiddenValue %>


Output : 









Note : If you get below error

 An error occurred at line: 1 in the jsp file: /submit.jsp renderRequest cannot be resolved

This may be because you missed to include <portlet:defineObjects /> in the jsp. The portlet specification defined this tag in order to be able to insert into the JSP a set of implicit variables that are useful for portlet developers such as renderRequest, portletConfig, portletPreferences, ... etc.