Liferay Important Code Snippets

Get Theme display object
<portlet:defineObjects />
<liferay-theme:defineObjects/>
<%=themeDisplay%>

Get PortletDisplay Object

themeDisplay.getPortletDisplay()


PortletConfigurationUrl

themeDisplay.getPortletDisplay().getURLConfiguration()


RenderURL creation

<portlet:renderURL var="configurationURL" windowState="pop_up">
 <portlet:param name="struts_action" value="/portlet_configuration/edit_configuration"></portlet:param>
 </portlet:renderURL>
=====================
  <portlet:renderURL var="sendEmailURL" windowState="<%= LiferayWindowState.EXCLUSIVE.toString() %>">
    <portlet:param name="jspPage" value="/html/adminfeedbackportlet/mailsent.jsp"/>
  </portlet:renderURL>



Use back url in JSP Pages:

<liferay-ui:header
            backURL="<%= backURL %>"
            title='<%= (organization == null) ? "new-organization" : organization.getName() %>'
/>


PropsValues class

public static final String[] ORGANIZATIONS_FORM_ADD_MAIN = PropsUtil.getArray(PropsKeys.ORGANIZATIONS_FORM_ADD_MAIN);
String[] mainSections = PropsValues.ORGANIZATIONS_FORM_ADD_MAIN;
String[] identificationSections = PropsValues.ORGANIZATIONS_FORM_ADD_IDENTIFICATION;
String[] miscellaneousSections = PropsValues.ORGANIZATIONS_FORM_ADD_MISCELLANEOUS;


Combine Multiple Arrays

String[] allSections = ArrayUtil.append(mainSections, ArrayUtil.append(identificationSections, miscellaneousSections));


Prevent Default Success Messages in Jsp Pages After Action performed.
Write this in portlet.xml file

<init-param>
            <name>add-process-action-success-action</name>
            <value>false</value>

 </init-param>


Get ThemeDisplay Object in Action Class

ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);


Form Submission through js and dynamic URL
submitForm(document.<portlet:namespace />fm, "<portlet:actionURL><portlet:param name="struts_action" value="/enterprise_admin/edit_organization" /></portlet:actionURL>");



Get Original HttpRequest in lifaray action class

PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(actionRequest))


Get Search Container IteratorURL

searchContainer.getIteratorURL();


If you want to change to logic say for just one action you can override the method

     protected void addSuccessMessage(
        ActionRequest actionRequest, ActionResponse actionResponse) {
        if (!addProcessActionSuccessMessage) {
            return; }
        String successMessage = ParamUtil.getString(
            actionRequest, "successMessage");
        SessionMessages.add(actionRequest, "request_processed", successMessage); }



Find organization and community

ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
long orgnizationId=0;
 com.liferay.portal.model.Group currentGroup =  themeDisplay.getLayout().getGroup();
 if (currentGroup.isOrganization()){
            orgnizationId = currentGroup.getClassPK();
 } else if (currentGroup.isCommunity() {
            orgnizationId = currentGroup.getGroupId();}}


Gets Session Messages

<c:if test='<%= SessionMessages.contains(renderRequest.getPortletSession(),"lore-request-added-successfully")%>'>
<liferay-ui:success key="lore-request-added-successfully" message="lore-request-added-successfully" />
</c:if>

           

AUI.IO.Request for Action URL
Liferay.provide(window,'<portlet:namespace />TestFunction',
function() {var A = AUI();
A.io.request('<portlet:actionURL><portlet:param name="javax.portlet.action" value="searchLoreBasedOnCategory" /></portlet:actionURL>',{
data: {directionsAddress:'meera',},
on: {failure: function() {alert("failure");},
success: function(event, id, obj) {
alert("sucess");}}});},'aui-io-request']);


jquery Ajax Function
jQuery.ajax({type : "POST",
url :"<%=feedbackActionURL.toString()%>", dataType : "html",
data: {user_Name:userName,feedBackType:feedBackType},
success:function(msg) {… },
error : function() {..}});



Hibernate Auto dll

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- This should be set to validate on production -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.format_sql">true</property>
        <property name="show_sql">true</property>
    </session-factory>
</hibernate-configuration>    


Important HttpRequest Methods
Actual Reqest for this: http://www.vidyayug.com:8080/c/portal/login?p_l_id=18009

request.getRemoteAddr()>> 127.0.0.1
request.getRemoteHost()>> 127.0.0.1
request.getRemotePort()>> 3899
request.getRequestURI()>> /c/portal/login
request.getLocalPort()>>  8080
request.getLocalAddr()>>  127.0.0.1
request.getPathInfo()>>    /portal/login
request.getQueryString()>> p_l_id=18009
request.getServerPort()>>  8080
request.getRequestURL()>> http://www.vidyayug.com:8080/c/portal/login


Display Session Messages

<c:if test="<%= SessionMessages.contains(portletRequest, key) %>">
            <div class="portlet-msg-success">
                        <c:choose>
                                    <c:when test="<%= translateMessage %>">
                                                <%= LanguageUtil.get(pageContext, message) %>
                                    </c:when>
                                    <c:otherwise>
                                                <%= message %>
                                    </c:otherwise>
                        </c:choose>
            </div>
</c:if>


Special Characters Regular Expression

var regExpression=/[&\/\\#,+()$~%.'":*?<>{}^!@|;?"`~]/;
var indiaMobileNumber = /^[7-9]\d*(?:\d+)?$/;


Sign In and Create Account URL with Icons

<liferay-ui:icon-list><liferay-ui:icon image="add_user" message="create-account"
url="<%= themeDisplay.getURLCreateAccount().toString() %>"/>
<liferay-ui:icon image="status_online" message="sign-in" url="<%= themeDisplay.getURLSignIn() %>"/>
</liferay-ui:icon-list>


Apply Liferay css to our messages
<div class="portlet-msg-info"> Please select a tool from the left menu.</div>
<div class="portlet-msg-success"> Please select a tool from the left menu.</div>
<div class="portlet-msg-error"> Please select a tool from the left menu.</div>


Liferay Tool Tip

<img alt="" onmouseover="Liferay.Portal.ToolTip.show(this, '<%=helpMessage %>');" src="/html/themes/control_panel/images/portlet/help.png" id="tooltipMessage">


Resource messages with variable values

loreshare-categories-count-message=Lore Share found more than {0} {1}.Hurry up you can search what you
<%= LanguageUtil.format(pageContext, "loreshare-categories-count-message",new String[]{String.valueOf(categoryBasedLoreCount),String.valueOf(loreCategoryName)})


Get Organization Logo
Organization organization = (Organization)request.getAttribute(WebKeys.ORGANIZATION);
long logoId = organization.getLogoId();
<%= themeDisplay.getPathImage() %>/organization_logo?img_id=<%= logoId %>&t=<%= ImageServletTokenUtil.getToken(logoId) %>


Call Portal Services through Java script API.
Below code give all countries which are in active state.

<script src="/html/js/liferay/service.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
function getCountry() {Liferay.Service.Portal.Country.getCountries({active:'<%=true%>'},
function(msg){alert(msg[0].countryId);});
}
</script>


The Following code in Entity ModelImpl class. If we set these properties in properties file then we can enable or disable cache for particular entity. This cache applicable foe Entity and Finder cache. By default it is true.
Following is we can write in property files.

value.object.entity.cache.enabled.YOUR ENTITY MODEL CLASS NAME WITH FULLY QUAKIFIED NAME=true/false
value.object.finder.cache.enabled.YOUR ENTITY MODEL CLASS NAME WITH FULLY QUAKIFIED NAME=true/false
lock.expiration.time.YOUR ENTITY MODEL CLASS NAME WITH FULLY QUAKIFIED NAME= its Number
public static final boolean ENTITY_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
"value.object.entity.cache.enabled.com.vidyayug.global.model.ApplicationParamGroup"),true);
public static final boolean FINDER_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
"value.object.finder.cache.enabled.com.vidyayug.global.model.ApplicationParamGroup"),true);
public static final long LOCK_EXPIRATION_TIME = GetterUtil.getLong(com.liferay.util.service.ServiceProps.get(                "lock.expiration.time.com.vidyayug.global.model.ApplicationParamGroup"));


Load Portal class and Portlet Classes
PortalClassLoaderUtil.getClassLoader().loadClass("com.liferay.portal.model.impl.UserImpl")
Ex:
query.addEntity("User_", PortalClassLoaderUtil.getClassLoader().loadClass("com.liferay.portal.model.impl.UserImpl"));
ClassLoader classLoader = (ClassLoader)PortletBeanLocatorUtil.locate(ClpSerializer.SERVLET_CONTEXT_NAME,
"portletClassLoader");
classLoader. loadClass("your portlet class name with fully qualified name");
Ex: query.addEntity("feedBack", classLoader.loadClass("com.vidyayug.global.model.impl.ApplicationParamGroupImpl"));


Get the Portlet level session Factory object.

private static SessionFactory  sessionFactory = (SessionFactory)PortalBeanLocatorUtil.locate("liferaySessionFactory");
session = sessionFactory.openSession();


Print log  messages in console:

private static Log _log = LogFactoryUtil.getLog(UniversalCommunicationAction.class);
_log.error("Number format exception whhile paring selected criteri id Cerittin Id migh not be expected value");
_log.info("this is json object====="+criteriaControlIdObject);


JQGrid:

jQuery('#list3').jqGrid('getGridParam','datatype')
jQuery('#list3').jqGrid('setGridParam',{page:1}).trigger('reloadGrid');
jQuery("#list3").jqGrid("clearGridData");
jQuery('#list3').jqGrid('getGridParam','reccount')
jQuery("#gridWrapper").hide();
var allrowssel_ids = grid.jqGrid('getGridParam', 'selarrrow');
var single row = jQuery("#list3").jqGrid('getGridParam','selrow');
var myCellData = grid.jqGrid('getCell', sel_ids[0], 'userId');


Get Phones List:
PhoneLocalServiceUtil.getPhones(String companyId, String className, String classPk)
Where companyId is the companyId you are using, classname is 'com.liferay.portal.model.Contact', and the classPk is the username you want.
This should return you a list of com.liferay.portal.model.Phone objects.


Check Method on Process Action This URL can only be invoked using POST

protected boolean isCheckMethodOnProcessAction() {
              return _CHECK_METHOD_ON_PROCESS_ACTION;
        }
private static final boolean _CHECK_METHOD_ON_PROCESS_ACTION = false;




Instance Factory is class creating instances for classes which are outside the current class loader.


Get Portlet Configuration URL
themeDisplay.getPortletDisplay().getURLConfiguration()


Get Organization URL

set ($test_url = (($theme_display.getPortalURL()) + "/" + ($theme_display.getLocale()) + ("/web") + ($group.getFriendlyURL()) + ("/sitemap")))



Load class and create object

Class<?> classObj=PortalClassLoaderUtil.getClassLoader().
loadClass("com.liferay.portlet.journal.model.impl.JournalArticleImpl");
JournalArticle journalArticleObj = (JournalArticle)classObj.newInstance();

Create URL for Portlet
PortletURL portletURL = PortletURLFactoryUtil.create(request,PortletKeys.PORTLET_CONFIGURATION, plid,PortletRequest.RENDER_PHASE);
portletURL.setParameter("struts_action", "/portlet_configuration/edit_permissions");
portletURL.setParameter("redirect", PortalUtil.getCurrentURL(request));
portletURL.setParameter("returnToFullPageURL",PortalUtil.getCurrentURL(request));
portletURL.setParameter("portletResource", "onceclicksite_WAR_OneclickSiteportlet");
portletURL.setParameter("resourcePrimKey", PortletPermissionUtil.getPrimaryKey(10296,"onceclicksite_WAR_OneclickSiteportlet"));
portletURL.setWindowState(LiferayWindowState.POP_UP);
portletURL.setPortletMode(PortletMode.VIEW);


Get Portlet List in Layout

LayoutTypePortlet layoutTypePortlet1 = (LayoutTypePortlet)layoutObject.getLayoutType();
              List<Portlet> portletList = layoutTypePortlet.getPortlets();


AUI Pop UP window
AUI().use('aui-dialog', 'aui-io', 'event', 'event-custom', function(A) {             
 var smsDialog = new A.Dialog({   title: 'Site Preview',  centered: true, draggable: true,
  modal: true, width:600, height:400}).plug(A.Plugin.IO, {uri:url,data:{ }}).render();
smsDialog.show();});


JQuery On Click Function
jQuery('#<portlet:namespace />publicLayoutSetPrototypeId').change(function(){
alert("this is meera");
});


Jquery Selected option value
var optioVal=jQuery('#<portlet:namespace />publicLayoutSetPrototypeId option:selected').val();
alert(jQuery(this).val());
alert(optioVal);
});


Jquery get Css property values
jQuery('#theid').css('display')
Jquery Add  Css property values
jQuery('#theid').css('display','none')


Jquery Add dynamic options
jQuery('#<portlet:namespace />siteDefaultRoles ').append( new Option(text,msg[0].val));
jQuery('#<portlet:namespace />siteDefaultRoles ').append('<option value="'+msg[k].categoryId+'" selected="selected">'+msg[k].categoryName+'</option>');


Jquery Bind events to element.
<input class="aui-field-input aui-field-input-text" id="eleId" name="elename" type="text" value="" selector="site-cutome-role-name">
 jQuery('[selector="site-cutome-role-name"]').bind('keypress keydown keyup', function(){
alert("this is in textt bxa key uppp");
jQuery('[selector="site-default-user-name"]').each(function() {
});});


jQuery Find element

jQuery("#siteCustomeRoles").find(".aui-field-input-select");


jQuery Empty method
Remove all child elements

jQuery("#siteCustomeRoles").find(".aui-field-input-select").empty();


jQuery remove method remove selected element and its Childs.


jQuery("#siteCustomeRoles").remove();


jQuery add attribute method to element

jQuery("#siteCustomeRoles").find(".aui-field-input-text").attr("placeholder", msg[k].categoryName);


jQuery after method
add element after sleelcted object

jQuery("#siteCustomeRoles").after(currentRow.html());



Creating Portlet URLs(renderURL/actionURL/resourceURL) in Liferay through jsp and javascript

Here I am creating renderURL only.Other URL's can be created in the similar way
 In JSP :
<portlet:renderURL var="renderURL ">
    <portlet:param name="param-name" value="param-value" />
    <portlet:param name="param-name" value="param-value" />
</portlet:renderURL>
OR
 <%
           PortletURL renderURL = renderResponse.createRenderURL();
           renderURL.setParameter("param-name", "param-value");
           renderURL.setParameter("param-name", "param-value");
%>


In the above example param-name could be "jspPage" and param-value could be "/html/edit.jsp" if you want to navigate from current jsp page to some other jsp page (in this case edit.jsp) . We can set other parameters also as per our requirements.

Inside your java script :
<script type="text/javascript">
function createRenderURL() {
    AUI().ready('liferay-portlet-url', function(A) {
        var renderURL = Liferay.PortletURL.createRenderURL();
        renderURL .setParameter("param-name","param-value");
        renderURL .setPortletId("your-unique-portlet-id");
        // i.e. your-unique-portlet-id can be like "helloworld_WAR_helloworldportlet"
    });
}
</script>


Note: Key point here is to set PortletId which is mandatory or else it would not be able to recognize the correct URL.
Playing with portletURL in Liferay
Without tld :
1.To get currentURL :
PortletURL url = PortletURLUtil.getCurrent(renderRequest, mimeResponse or renderResponse)


2. To make clone of a URL:
PortletURL url = PortletURLUtil.clone(portletURL, mimeResponse or renderResponse)


3. Creating PortletURL from action Response:

PortletURL renderURL = ((ActionResponseImpl) actionResponse).createRenderURL();


4. Creating PortletURL from render Response:
a.For RenderURL:
PortletURL renderURL = renderResponse.createRenderURL();
b.For actionURL:
PortletURL actionURL = renderResponse.createActionURL();


5. Using TLD's in Life ray :
a.
<portlet:renderURL windowState="<%= WindowState.ur_state.toString() %>">
<portlet:param name="param_name" value="param_value" />
<portlet:param name="param_name" value="param_value" />
</portlet:renderURL>
b.
<portlet:actionURL windowState="<%= WindowState.ur_state.toString() %>">
<portlet:param name="param_name" value="param_value" />
<portlet:param name="param_name" value="param_value" />
</portlet:actionURL>



If you put the *-service.jar inside the tomcat/lib/ext then you should remove it from your custom-portlet's WEB-INF/lib/.
I would suggest using the following property in your liferay-plugin-package.properties in all other portlets which use the services of MyCommon-portlet:
required-deployment-contexts=MyCommon-portlet
Only put the *-service.jar inside the tomcat/lib/ext when you need that your *-service.jar's method should be available to even the Hooks or EXTs you would create. For custom plugin portlets the liferay-plugin-package.properties should suffice.




Share on Google Plus

About Meera Prince

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

1 comments:

  1. Hello Hyd prince. I'm new with liferay's development. The company where I work has allocated me in a job with liferay. I'm having some trouble with search-containers. I'd like to know if you can help me with some answers.
    Thanks,

    contact me at :glourenco@vertigo.com.br

    ReplyDelete