Tuesday, May 12, 2015

AJAX Server Side Validations in Liferay Example 1

Step 1 : Create one portlet plugin project , project name in our case ajaxServerSideValidation,
inside project create one portlet and give portlet class name ServerSideValidation.

Step 2 : Paste below code in portlet view.jsp

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

<portlet:defineObjects />


<h1>Liferay Ajax Server Side Validation</h1><br/>


<h3>User Registration</h3>

<portlet:actionURL var="userRegistrationActionURL" windowState="normal" name="createUserAccount"/>

<portlet:resourceURL var="resourceURL"/>



 <aui:form action="<%=userRegistrationActionURL%>" name="userRegistartionForm" id="userRegistartionForm" method="POST">      
    <div style="display:none;" id="<portlet:namespace/>screenExistanceErrorMessage">
             <p style="color:red;">* Screen Name Already Exist, Please Use Any other</p>
    </div>
    <aui:input name="screeName" id="screeName" label="User Screen Name"/>
       
    <div style="display:none;" id="<portlet:namespace/>emailExistanceErrorMessage">
             <p style="color:red;">* Email Id Already Exist, Please Use Any other</p>
    </div>  
    <aui:input name="emailAddress" id="emailAddress" label="User Email Address"/>
         
    <aui:button type="button" name="addUser" id="addUser" value="Create User Account"/>
</aui:form> 

 <!-- or we can use normal form also -->


<%--  <form action="<%=userRegistrationActionURL%>" name="<portlet:namespace/>userRegistartionForm" id="<portlet:namespace/>userRegistartionForm" method="POST">
  
      <div style="display:none;" id="<portlet:namespace/>screenExistanceErrorMessage">
             <p style="color:red;">* Screen Name Already Exist, Please Use Any other</p>
      </div>
      User Screen Name :<input type="text" name="<portlet:namespace/>screeName" id="<portlet:namespace/>screeName" /><br />
  
      <div style="display:none;" id="<portlet:namespace/>emailExistanceErrorMessage">
             <p style="color:red;">* Email Id Already Exist, Please Use Any other</p>
      </div> 
      User Email Address :<input type="text" name="<portlet:namespace/>emailAddress" id="<portlet:namespace/>emailAddress" /><br />
      
      <input type="button" name="<portlet:namespace/>addUser" id="<portlet:namespace/>addUser" value="Create User Account" />
</form>
 --%>

<aui:script>
    AUI().use('aui-base','aui-io-request','aui-node', function(A){
        
        var userEmailValidation=false;
        var userScreenNameValidation=false;
        
        // this function will call on screenName field on blur
        A.one("#<portlet:namespace/>screeName").on('blur',function(){
        //aui ajax call
        var screeName=A.one("#<portlet:namespace/>screeName").get("value");
        A.io.request('<%=resourceURL%>',{
        dataType : 'json',
        method : 'GET',
        data : {
        <portlet:namespace/>screeName :screeName,
        <portlet:namespace/>cmd:'SCREENNAME'
        },
        on : {
        success : function() {
        var data = this.get('responseData');
        var isScreenNameExist=data.screenNameExist;
        
        if(isScreenNameExist=='true'){
               A.one("#<portlet:namespace/>screeName").setStyle('border','1px solid red');
               A.one('#<portlet:namespace />screenExistanceErrorMessage').show();
               
               userScreenNameValidation=false;
        }
        if(isScreenNameExist=='false'){
               A.one("#<portlet:namespace/>screeName").setStyle('border','1px solid green');
               A.one('#<portlet:namespace />screenExistanceErrorMessage').hide();
               
               userScreenNameValidation=true;
        }
        
        }
        }
        });
        });
        
        // this function will call on email field on blur
        A.one("#<portlet:namespace/>emailAddress").on('blur',function(){
        var emailAddress=
        A.one("#<portlet:namespace/>emailAddress").get("value");
        A.io.request('<%=resourceURL%>',{
        dataType : 'json',
        method : 'GET',
        data : {
        <portlet:namespace/>emailAddress :emailAddress,
        <portlet:namespace/>cmd:'EMAIL'
        },
        on : {
        success : function() {
        var data = this.get('responseData');
        var isEmailExist=data.emailExist;
        
        if(isEmailExist=='true'){
                A.one("#<portlet:namespace/>emailAddress").setStyle('border','1px solid red');
                A.one('#<portlet:namespace />emailExistanceErrorMessage').show();
                
                userEmailValidation=false;
        }
        if(isEmailExist=='false'){
                A.one("#<portlet:namespace/>emailAddress").setStyle('border','1px solid green');
                A.one('#<portlet:namespace />emailExistanceErrorMessage').hide();
                
                userEmailValidation=true;
        }
        
        }
        }
        });
        });
        A.one('#<portlet:namespace/>addUser').on('click', function(event){
        if(userEmailValidation==true&& userScreenNameValidation==true){
        document.<portlet:namespace/>userRegistartionForm.submit();
        }
        });
        
    });
</aui:script>



Explanation : In above  code we are taking email address and screen name in AUI funtion using aui script and then calling serve resource method using on blur function on email address and screen name field.
If email id and screen name passed by user is not avaialble /not matched with database record then only onclik function will call on input botton field and call action method to submit form data and in action method we can write logic of adding user detail into database.

Step 3 : Paste below code in portlet controller class ServerSideValidation

package com.test;

import java.io.IOException;
import java.io.PrintWriter;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * Portlet implementation class ServerSideValidation
 */
public class ServerSideValidation extends MVCPortlet {

     public void createUserAccount(ActionRequest actionRequest,
             ActionResponse actionResponse) throws IOException, PortletException {
            
        
             String screeName = ParamUtil.getString(actionRequest, "screeName");
             String emailAddress = ParamUtil.getString(actionRequest, "emailAddress");
            
             System.out.println("screen name :" +screeName);
             System.out.println("email address :"+ emailAddress);
        }

             @Override
             public void serveResource(ResourceRequest resourceRequest,
             ResourceResponse resourceResponse) throws IOException,
             PortletException {
                
                
                 System.out.println("inside serve resource...");
                
             JSONObject jsonUser = JSONFactoryUtil.createJSONObject();
             String cmd = ParamUtil.getString(resourceRequest, "cmd");
            // System.out.println("====serveResource===cmd====="+cmd);
             String emailAddress = ParamUtil.getString(resourceRequest,"emailAddress");
             String screeName = ParamUtil.getString(resourceRequest, "screeName");
             if (cmd.equals("EMAIL")) {
             emailValidation(resourceRequest,resourceResponse,emailAddress);
             }
             if (cmd.equals("SCREENNAME")) {
             screenNameValidation(resourceRequest,resourceResponse,screeName);
             }
             }
            
             public void screenNameValidation(ResourceRequest resourceRequest,
             ResourceResponse resourceResponse,String screeName) throws IOException,
             PortletException {
                
                 System.out.println("inside screenname....");
                
             User user = null;
             JSONObject jsonUser = JSONFactoryUtil.createJSONObject();
             ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
             try {
             user = UserLocalServiceUtil.getUserByScreenName(themeDisplay.getCompanyId(), screeName);
             if (user != null) {
             jsonUser.put("screenNameExist", "true");
             }
             } catch (PortalException e) {
             jsonUser.put("screenNameExist", "false");
             } catch (SystemException e) {
             jsonUser.put("screenNameExist", "false");
             }
             PrintWriter out = resourceResponse.getWriter();
             out.println(jsonUser.toString());
             }
            
            
            
             public void emailValidation(ResourceRequest resourceRequest,
             ResourceResponse resourceResponse,String emailAddress) throws IOException,
             PortletException {
                
                 System.out.println("inside email validation");
                
                 User user = null;
                 JSONObject jsonUser = JSONFactoryUtil.createJSONObject();
                 ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
                 try {
                 user = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(), emailAddress);
                 if (user != null) {
                 jsonUser.put("emailExist", "true");
                 } else {
                 jsonUser.put("emailExist", "false");
                 }
                 } catch (PortalException e) {
                
                 jsonUser.put("emailExist", "false");
                 } catch (SystemException e) {
                
                 jsonUser.put("emailExist", "false");
                 }
    
                 PrintWriter out = resourceResponse.getWriter();
                 out.println(jsonUser.toString());
             }
}


Explanation : In above code we are getting field value in server resource method and validating email and screen name with database value, if email address and screen name passed by user is not available in database then only form submission will happen and will call action method.
If values are matched with database value then serve resource method will return error message.

Now deploy your portlet.

OutPut :
For testing try to give screen name and/or emai id which is already registered in database.
If there is no user registered in database then you can create user manully from controll panel also.
In our case i have created one user using controll panel in liferay database screen name rehan
and email id azharuddinmd864@gmail.com.



0 comments:

Post a Comment