Tuesday, April 28, 2015

Call Action URL using javascript function in Liferay

Sometimes we will get a requirement that we need to hit the "Action URL" using java script function.
May be my blog will be help you fot that requirement.

   <%
           PortletURL actionURL = renderResponse.createActionURL();
           actionURL.setParameter(ActionRequest.ACTION_NAME, "getPrice");
    %>
// creating action URL which will hit the Action method called "getPrice".

<aui:form name="fm" method="POST" >

<aui:input type="text" name="price" label=""  required="true"  onclick="getPrice()" inlineLabel="true">
                                    <aui:validator name="number"></aui:validator>
                                </aui:input>

<aui:button-row>
                    <aui:button type="submit" for="Submit" key="submit" value="Submit"/>                 </aui:button-row>
</aui:form>

// I have created one form with one text field  when i click that field i need to call getPrice action URL

<script>
        function getPrice() {
            document.<portlet:namespace/>fm.action = '<%=actionURL.toString()%>';
            document.<portlet:namespace/>fm.submit();
        }

    </script>

// The above javascript code is usefull  to hit the aciton URL with javascript function without clicking the submit button through javascript we are clicking the submit button.

Hope this is helpfull for you

Friday, April 17, 2015

Properties Entry while working with Ajax calls in Liferay

Some times Ajax call will not work properly in liferay,  when you are passing parameters you will face some issues like not able to pass the values through Ajax call then add the following tags in liferay-portlet.xml
<requires-namespaced-parameters>false</requires-namespaced-parameters>
  <ajaxable>true</ajaxable>

Tuesday, September 9, 2014

Auto complete using Ajax Call Using in Liferay

some times we will have a requirement of auto-complete feature like google search, 

ex:- when ever you search for the particular employee name you need to fetch all employee names which will match or start with the particular character or word. The below code will help you to achieve that requirement.


jsp code :-

//created the resource URL to hit the serveResource method.

<portlet:resourceURL var="getEmployeeNames"/>

// Input field where you need to enter the characters of employee name for example

<aui:input id="myInputNode" name="myInputNode" label="ms-std-rep" helpMessage="Type MS Standard Name in Input Box"/>

// script code to perform auto complete feature.

<script type="text/javascript">

 AUI().use('autocomplete-list','aui-base','aui-io-request','autocomplete-filters','autocomplete-highlighters',function (A) {
    A.io.request('<%=getEmployeeNames%>',{
            dataType: 'json',
            method: 'GET',
            on: {
                success: function() {
                new A.AutoCompleteList(
                {
                allowBrowserAutocomplete: 'true',
                activateFirstItem: 'true',
                inputNode: '#myInputNode',
                resultTextLocator: 'result',
                resultHighlighter:['phraseMatch'],
                resultFilters:['phraseMatch'],
                render: 'true',
                source:this.get('responseData'),
                });
    }}
    }); 

    });
</script>

Note :-
we can get the values in different ways of matching scenarios depending upon the value given to the " resultFilters "

charMatch: gives the results that contain all of the individual characters in the query, in any order (not necessarily consecutive).
phraseMatch: gives the results that contain the complete query as a phrase.
startsWith: gives the results that start with the complete query as a phrase.
subWordMatch: gives the results in which all the words of the query match either whole words or parts of words in the result. Non-word characters like whitespace and certain punctuation are ignored.
wordMatch: gives the results that contain all the individual words in the query, in any order (not necessarily consecutive).
ex:-
 resultFilters: ['charMatch', 'wordMatch']


java code :- This code should be write in the Action class of your portlet.

import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;

import java.io.PrintWriter;


@Override
    public void serveResource(ResourceRequest resourceRequest, ResourceResponse
            resourceResponse) throws IOException, PortletException {
        _log.info("Starting of Serve Resource Method");
        getResults(resourceRequest,resourceResponse);
        _log.info("Exit of Serve Resource Method");
    }

public void getResults(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
           PrintWriter out;
        JSONArray usersJSONArray = JSONFactoryUtil.createJSONArray();
        JSONObject userJSON=null;
        String mystring = StringPool.BLANK;
        try {
            List  list=MLocalServiceUtil.getM(0,MLocalServiceUtil.getMCount());
            for(M mobj:list){
                  mystring= "result values"; // values which you need to pass to jsp ex: mobj.usernmae                        userJSON=JSONFactoryUtil.createJSONObject();
                    userJSON.put("result",mystring);
                    usersJSONArray.put(userJSON);
                }
            out = resourceResponse.getWriter();
            out.println(usersJSONArray.toString());
        }
        catch (SystemException e) {
                    }
        catch (IOException e) {
                   }
          }

Journal Article in template file / vm file Liferay



If we want to fetch the journal article of web content details in template file then the following code will be usefull.
The following code will shows the tag based journal Article content in template.
  
#set($assetTag =$serviceLocator.findService('com.liferay.portlet.asset.service.AssetTagLocalService'))
#set($assetEntryService =$serviceLocator.findService('com.liferay.portlet.asset.service.AssetEntryLocalService'))
#set($journalArticleResourceLocal=$serviceLocator.findService('com.liferay.portlet.journal.service.JournalArticleResourceLocalService'))
#set($journalArticleLocal=$serviceLocator.findService('com.liferay.portlet.journal.service.JournalArticleLocalService'))
#set($journalContentUtil =$utilLocator.findUtil('com.liferay.portlet.journalcontent.util.JournalContent'))
#set($groupId = $getterUtil.getLong($groupId))
#set($languageId = $request.theme-display.language-id)

#set($assetTagObj=$assetTag.getTag($groupId,"myTag"))
    #set($assetId = $assetTagObj.getTagId())
    #set($assestList= $assetEntryService.getAssetTagAssetEntries($assetId))
    #set($assetEntry = "")
#foreach($assetEntry in $assestList)
         #set($journalArticleResource =$journalArticleResourceLocal.getJournalArticleResource($assetEntry.getClassPK()))
         #set($journalArticle = $journalArticleLocal.getArticle($groupId,$journalArticleResource.getArticleId()))
         #set($latestArticle= $journalArticleLocal.getLatestArticle($groupId,$journalArticle.getArticleId()))
         #set( $journalArticleDisplay= $journalContentUtil.getDisplay($groupId,$latestArticle.getArticleId(), null,null,$languageId,null, 1, $xmlRequest))
            $journalArticleDisplay.getContent()
        #end

Different Ways of Getting Journal Article Content / Web Content in Liferay Portlet


Getting the Journal Article of Particular Name :-


If we want to fetch the specific name web content details then the following code will be useful.
String articleName =  "mPower";  // I need the mPower web content details
    String content = StringPool.BLANK;

    JournalArticle journalArticle = JournalArticleLocalServiceUtil.getArticleByUrlTitle (themeDisplay.getScopeGroupId(), articleName); // getting the journalArticle Object based on name

            String articleId = journalArticle.getArticleId();

            JournalArticleDisplay articleDisplay =  JournalContentUtil.getDisplay (themeDisplay.getScopeGroupId(), articleId,"",themeDisplay.getLanguageId(),themeDisplay);

            content = articleDisplay.getContent(); // by using display content object I am fetching the data of my mPower Web content.


Getting the Journal Article based on Tag Name :-



If we want to fetch the specific tag based  web content details then the following code will be useful.


String content = StringPool.BLANK;

AssetTag assetTag = AssetTagLocalServiceUtil.getTag(themeDisplay.getScopeGroupId(), "mytagname");
    long assetTagId = assetTag.getTagId();
    List assetEntrylist = AssetEntryLocalServiceUtil.getAssetTagAssetEntries(assetTagId);

for(AssetEntry assetEntry : assetEntrylist) {
        JournalArticleResource journalArticleResourceObj = JournalArticleResourceLocalServiceUtil.getJournalArticleResource(assetEntry.getClassPK());
        JournalArticle journalArticleObj = JournalArticleLocalServiceUtil.getArticle(themeDisplay.getScopeGroupId(),journalArticleResourceObj.getArticleId());
        String articleId = journalArticleObj.getArticleId();
        JournalArticleDisplay articleDisplay =  JournalContentUtil.getDisplay (themeDisplay.getScopeGroupId(), articleId,"",themeDisplay.getLanguageId(),themeDisplay);
        content = articleDisplay.getContent();

}

Getting the Journal Article based on Structure Id  or Template Id:-


If we want to fetch the specific Structure of template based  web content details then the following code will be useful

  String content = StringPool.BLANK;
List articleList = JournalArticleLocalServiceUtil.getStructureArticles(themeDisplay.getScopeGroupId(), "15916");
 // for template use API  getTemplateArticles
for(JournalArticle journalArticle : articleList) {

String articleId = journalArticle.getArticleId();

            JournalArticleDisplay articleDisplay =  JournalContentUtil.getDisplay (themeDisplay.getScopeGroupId(), articleId,"",themeDisplay.getLanguageId(),themeDisplay);

            content = articleDisplay.getContent();
}


Tuesday, July 15, 2014

Image Validation Using Script

AUI().ready('event','node',function(A){

imgCheck=function(){
alert("Image Checking");
var elem = A.one("#<portlet:namespace/>cover").val();
var parts = elem.split('.');
var imgformat = parts[parts.length - 1];
switch (imgformat.toLowerCase()) {
case 'jpg':
case 'gif':
case 'bmp':
case 'png':
case 'jpeg':
return true;
}
alert("Please Upload Correct Image Format");
A.one("#<portlet:namespace/>cover").val("");
return false

};
});

Liferay DXP JNDI Data Source Cofiguration

 This Blog will help us to learn about the JNDI Data Source Configuration in Liferay DXP. We have tested this with Liferay 7.3 with Tomcat. ...