Sunday, August 2, 2015

Liferay jQuery Data Table

JQuery Data table is way of present our data at client side and we can show case data and we can perform operations like sorting, update, page nation and many other operations we can perform on data table.

JQuery Data table is very popular jQuery plugin which built it on top of JQuery library. JQuery Data table have very good community and plenty of example so that we can use and integrate to our applications.

The following is reference URL


Liferay have search container to display data and make pagination and sorting apart from if you want use some other data gird/data table then JQuery data table is best choice and we can better  support and many examples available.

As we know that JQuery Data table have used JQuery Java script library and its one of plugin for JQuery.

When we want integrate JQuery Data table we need JQuery Core library java scrip, Data table Plugin and Data table required CSS.

Download Liferay JQuery Data Table Portlet


The following are minimum required files.


JavaScript Files

jquery-1.11.1.min.js
jquery.dataTables.min.js

CSS Files

jquery.dataTables.css

Note:

Above specified files available in direct at CDN point we can use those reference or we directly put in our application then refer them, either way is fine.


JQuery Data Table have many examples all example available in the following URL


Down load all Data table related files


JQuery Data table developed with minimum required needs apart from that it we want enable out of box features then we have data table extension and  data table plugins. When we use these then we will get additional capabilities for data tables.



JQuery Data table have API document there we can see all properties and methods which are available in data table.


General Example of Data Table


<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.7/css/jquery.dataTables.css">

 <script>
 $(document).ready(function() {
                $('#userTable').DataTable();
            } );
 </script>
</head>
<body>
<table id="userTable" class="display" cellspacing="0" width="100%">
       <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
            <tr>
                <td>Garrett Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>63</td>
                <td>2011/07/25</td>
                <td>$170,750</td>
            </tr>
            <tr>
                <td>Ashton Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
                <td>66</td>
                <td>2009/01/12</td>
                <td>$86,000</td>
            </tr>
            <tr>
                <td>Cedric Kelly</td>
                <td>Senior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>22</td>
                <td>2012/03/29</td>
                <td>$433,060</td>
            </tr>
            <tr>
                <td>Airi Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>33</td>
                <td>2008/11/28</td>
                <td>$162,700</td>
            </tr>
            <tr>
                <td>Brielle Williamson</td>
                <td>Integration Specialist</td>
                <td>New York</td>
                <td>61</td>
                <td>2012/12/02</td>
                <td>$372,000</td>
            </tr>
            <tr>
                <td>Herrod Chandler</td>
                <td>Sales Assistant</td>
                <td>San Francisco</td>
                <td>59</td>
                <td>2012/08/06</td>
                <td>$137,500</td>
            </tr>
            <tr>
                <td>Rhona Davidson</td>
                <td>Integration Specialist</td>
                <td>Tokyo</td>
                <td>55</td>
                <td>2010/10/14</td>
                <td>$327,900</td>
            </tr>
            <tr>
                <td>Colleen Hurst</td>
                <td>Javascript Developer</td>
                <td>San Francisco</td>
                <td>39</td>
                <td>2009/09/15</td>
                <td>$205,500</td>
            </tr>
            <tr>
                <td>Sonya Frost</td>
                <td>Software Engineer</td>
                <td>Edinburgh</td>
                <td>23</td>
                <td>2008/12/13</td>
                <td>$103,600</td>
            </tr>
        </tbody>
    </table>
</body>
</html>


JQuery Data table have rich set of methods and Properties from these we can full fill our need in the development of applications.

In this post I will take some examples from JQuery Data table and make it work in Liferay Portlet.

Simple Data Table
Load Data in Data Table Using Ajax
Hidden Data Table Columns

Simple Data Table

Simple data table we simply get data from data and present in the JSP page. Here we need to add required JS and CSS files. I already added JS and CSS files in portlet so we simply refer ethos files.

Simple Data Table Example


<%@page import="com.liferay.portal.model.User"%>
<%@page import="com.liferay.portal.service.UserLocalServiceUtil"%>
<%@include file="init.jsp" %>
<script src="<%=renderRequest.getContextPath()%>/js/jquery-1.11.1.min.js"></script>
<script src="<%=renderRequest.getContextPath()%>/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="<%=renderRequest.getContextPath()%>/css/jquery.dataTables.css">
<style>
.message-container{
 padding:10px;
 margin:2px;
 display:none;
 background: rgba(128, 128, 128, 0.33);
 border: 1px solid #0A0A0C;
 }
</style>
<h2>Simple Jquery Data Table with Zero Configuration</h2>
<%
List<User> userList=UserLocalServiceUtil.getUsers(-1,-1);
%>
<c:if test="<%=userList!=null&&!userList.isEmpty() %>">
<table id="userTable" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </tfoot>
        <tbody>
        <%for(User curUser:userList){ %>
            <tr>
                <td><%=curUser.getUserId()%></td>
                 <td><%=curUser.getScreenName()%></td>
                 <td><%=curUser.getFirstName()%></td>
                 <td><%=curUser.getLastName()%></td>
                 <td><%=curUser.getEmailAddress()%></td>
                 <td><%=curUser.getJobTitle()%></td>
            </tr>
          <%} %>
        </tbody>
    </table>
 <script>
 $(document).ready(function() {
                $('#userTable').DataTable();
            } );
 </script>
 </c:if>
 <c:if test="<%=Validator.isNull(userList)||userList.isEmpty()%>">
 <div class="message-container">No data to Display</div>
 </c:if>


Load Data in Data Table Using Ajax

In this example we will use Ajax call to Portlet server resource method there we will prepare JSON data as for data table required format so that data will be loaded in the table.

Data as Array


Data Table Java Script

$(document).ready(function() {
                $(document).ready(function() {
                    $('#userTable').dataTable( {
                        "ajax": "<%=usersArrayURL%>"
                    } );
                } );
} );

Data Format

{
   "data":[
      [
         20199,
         "joebloggs",
         "Joe",
         "Bloggs",
         "test@liferay.com",
         ""
      ],
      [
         20536,
         "ord1",
         "Test",
         "ORD 1",
         "test.ord.1@liferay.com",
         ""
      ],
      [
         20543,
         "ord2",
         "Test",
         "ORD 2",
         "test.ord.2@liferay.com",
         ""
      ],
      [
         20550,
         "ord3",
         "Test",
         "ORD 3",
         "test.ord.3@liferay.com",
         ""
      ]
   ]
}


Data as Array of Objects

Here data is array of user objects and this will be referred by key “data” in the object.


Data Table Java Script

$(document).ready(function() {
                $('#userTable').dataTable( {
                    "ajax": "<%=usersObjectArrayURL%>",
                    "columns": [
                        { "data": "userId" },
                        { "data": "screeName" },
                        { "data": "firstName" },
                        { "data": "lastName" },
                        { "data": "email" },
                        { "data": "jobTitle" }
                    ]
                } );
            } );

Data Format

{
   "data":[
      {
         "lastName":"Bloggs",
         "email":"test@liferay.com",
         "screeName":"joebloggs",
         "userId":20199,
         "firstName":"Joe",
         "jobTitle":""
      },
      {
         "lastName":"ORD 1",
         "email":"test.ord.1@liferay.com",
         "screeName":"ord1",
         "userId":20536,
         "firstName":"Test",
         "jobTitle":""
      },
      {
         "lastName":"ORD 2",
         "email":"test.ord.2@liferay.com",
         "screeName":"ord2",
         "userId":20543,
         "firstName":"Test",
         "jobTitle":""
      },
      {
         "lastName":"ORD 3",
         "email":"test.ord.3@liferay.com",
         "screeName":"ord3",
         "userId":20550,
         "firstName":"Test",
         "jobTitle":""
      }
   ]
}


Flat Data

In this example data will be like array of user objects and in the scrip we need to specify the column names and these should match to JSON object keys.


Data Table Java Script

$(document).ready(function() {
                $('#userTable').dataTable( {
                    "ajax": {
                      "url":"<%=usersFlatDataSourceURL%>",
                      "dataSrc": ""
                     },
                    "columns": [
                        { "data": "userId" },
                        { "data": "screeName" },
                        { "data": "firstName" },
                        { "data": "lastName" },
                        { "data": "email" },
                        { "data": "jobTitle" }
                    ]
                } );
            } );

Data Format

[
   {
      "lastName":"Bloggs",
      "email":"test@liferay.com",
      "screeName":"joebloggs",
      "userId":20199,
      "firstName":"Joe",
      "jobTitle":""
   },
   {
      "lastName":"ORD 1",
      "email":"test.ord.1@liferay.com",
      "screeName":"ord1",
      "userId":20536,
      "firstName":"Test",
      "jobTitle":""
   },
   {
      "lastName":"ORD 2",
      "email":"test.ord.2@liferay.com",
      "screeName":"ord2",
      "userId":20543,
      "firstName":"Test",
      "jobTitle":""
   },
   {
      "lastName":"ORD 3",
      "email":"test.ord.3@liferay.com",
      "screeName":"ord3",
      "userId":20550,
      "firstName":"Test",
      "jobTitle":""
   }
]


Custom Data Source Property

Here we will refer our data as “mytabledata” key in JSON object same key we have to use in the script for property “dataSrc


Data Table Java Script

$(document).ready(function() {
                $('#userTable').dataTable( {
                    "ajax": {
                      "url":"<%=usersCustomDataSourceURL%>",
                      "dataSrc": "mytabledata"
                     },
                    "columns": [
                        { "data": "userId" },
                        { "data": "screeName" },
                        { "data": "firstName" },
                        { "data": "lastName" },
                        { "data": "email" },
                        { "data": "jobTitle" }
                    ]
                } );
            } );

Data format

{
   "mytabledata":[
      {
         "lastName":"Bloggs",
         "email":"test@liferay.com",
         "screeName":"joebloggs",
         "userId":20199,
         "firstName":"Joe",
         "jobTitle":""
      },
      {
         "lastName":"ORD 1",
         "email":"test.ord.1@liferay.com",
         "screeName":"ord1",
         "userId":20536,
         "firstName":"Test",
         "jobTitle":""
      },
      {
         "lastName":"ORD 2",
         "email":"test.ord.2@liferay.com",
         "screeName":"ord2",
         "userId":20543,
         "firstName":"Test",
         "jobTitle":""
      },
      {
         "lastName":"ORD 3",
         "email":"test.ord.3@liferay.com",
         "screeName":"ord3",
         "userId":20550,
         "firstName":"Test",
         "jobTitle":""
      }
            ]
}


Hidden Data Table Columns

Sometime data we may have many columns but some of columns you want hidden while display in table that we can do with following script and we need specify the columns index that you are going to hide.


Html

<table id="userTable" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </tfoot>
    </table>

Java Script

$(document).ready(function() {
                $('#userTable').dataTable( {
                    "ajax": "<%=usersObjectArrayURL%>",
                    "columns": [
                        { "data": "userId" },
                        { "data": "screeName" },
                        { "data": "firstName" },
                        { "data": "lastName" },
                        { "data": "email" },
                        { "data": "jobTitle" }
                    ],
                    "columnDefs": [
                                   {
                                       "targets": [ 0 ],
                                       "visible": false,
                                       "searchable": false
                                   },
                                   {
                                       "targets": [ 5 ],
                                       "visible": false
                                   }
                               ]
                } );
            } );


Complete Code Example

Simple Data Table Example


<%@page import="com.liferay.portal.model.User"%>
<%@page import="com.liferay.portal.service.UserLocalServiceUtil"%>
<%@include file="init.jsp" %>
<script src="<%=renderRequest.getContextPath()%>/js/jquery-1.11.1.min.js"></script>
<script src="<%=renderRequest.getContextPath()%>/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="<%=renderRequest.getContextPath()%>/css/jquery.dataTables.css">
<style>
.message-container{
 padding:10px;
 margin:2px;
 display:none;
 background: rgba(128, 128, 128, 0.33);
 border: 1px solid #0A0A0C;
 }
</style>
<h2>Simple Jquery Data Table with Zero Configuration</h2>
<%
List<User> userList=UserLocalServiceUtil.getUsers(-1,-1);
%>
<c:if test="<%=userList!=null&&!userList.isEmpty() %>">
<table id="userTable" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </tfoot>
        <tbody>
        <%for(User curUser:userList){ %>
            <tr>
                <td><%=curUser.getUserId()%></td>
                 <td><%=curUser.getScreenName()%></td>
                 <td><%=curUser.getFirstName()%></td>
                 <td><%=curUser.getLastName()%></td>
                 <td><%=curUser.getEmailAddress()%></td>
                 <td><%=curUser.getJobTitle()%></td>
            </tr>
          <%} %>
        </tbody>
    </table>
 <script>
 $(document).ready(function() {
                $('#userTable').DataTable();
            } );
 </script>
 </c:if>
 <c:if test="<%=Validator.isNull(userList)||userList.isEmpty()%>">
 <div class="message-container">No data to Display</div>
 </c:if>


Load Data Using Ajax as Array of Objects


JSP Page

<%@page import="com.liferay.portal.model.User"%>
<%@page import="com.liferay.portal.service.UserLocalServiceUtil"%>
<%@include file="init.jsp" %>
<script src="<%=renderRequest.getContextPath()%>/js/jquery-1.11.1.min.js"></script>
<script src="<%=renderRequest.getContextPath()%>/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="<%=renderRequest.getContextPath()%>/css/jquery.dataTables.css">
<portlet:resourceURL var="usersObjectArrayURL">
            <portlet:param name="cmd" value="jsonUserObjectArray"/>
</portlet:resourceURL>
<style>
.message-container{
 padding:10px;
 margin:2px;
 display:none;
 background: rgba(128, 128, 128, 0.33);
 border: 1px solid #0A0A0C;
 }
</style>
<h2>Jquery Data Table with Array Of Ojbects from Server Through Ajax</h2>
<table id="userTable" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </tfoot>
    </table>
 <script>
 $(document).ready(function() {
                $('#userTable').dataTable( {
                    "ajax": "<%=usersObjectArrayURL%>",
                    "columns": [
                        { "data": "userId" },
                        { "data": "screeName" },
                        { "data": "firstName" },
                        { "data": "lastName" },
                        { "data": "email" },
                        { "data": "jobTitle" }
                    ]
                } );
            } );
 </script>

Portlet Serve Resource Code

public void arrayOfJSONUserObjects(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws IOException,
PortletException {
JSONArray usersJsonArray = JSONFactoryUtil.createJSONArray();
try {
logger.info("====serveResource========");
JSONObject jsonUser = null;

List<User> userList = UserLocalServiceUtil.getUsers(1,UserLocalServiceUtil.getUsersCount());
for (User userObj : userList) {
jsonUser = JSONFactoryUtil.createJSONObject();
jsonUser.put("userId", userObj.getUserId());
jsonUser.put("screeName", userObj.getScreenName());
jsonUser.put("firstName", userObj.getFirstName());
jsonUser.put("lastName", userObj.getLastName());
jsonUser.put("email", userObj.getEmailAddress());
jsonUser.put("jobTitle", userObj.getJobTitle());
usersJsonArray.put(jsonUser);
}
} catch (Exception e) {
e.printStackTrace();
}

JSONObject tableData = JSONFactoryUtil.createJSONObject();
tableData.put("data", usersJsonArray);
logger.info("tableData:"+tableData.toString());
ServletResponseUtil.write(PortalUtil.getHttpServletResponse(resourceResponse),
tableData.toString());
}


Load Data Using Ajax as Array


JSP Page

<%@page import="com.liferay.portal.model.User"%>
<%@page import="com.liferay.portal.service.UserLocalServiceUtil"%>
<%@include file="init.jsp" %>
<script src="<%=renderRequest.getContextPath()%>/js/jquery-1.11.1.min.js"></script>
<script src="<%=renderRequest.getContextPath()%>/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="<%=renderRequest.getContextPath()%>/css/jquery.dataTables.css">
<portlet:resourceURL var="usersArrayURL">
            <portlet:param name="cmd" value="jsonUsersArray"/>
</portlet:resourceURL>
<style>
.message-container{
 padding:10px;
 margin:2px;
 display:none;
 background: rgba(128, 128, 128, 0.33);
 border: 1px solid #0A0A0C;
 }
</style>
<h2>Jquery Data Table with Array Data from Server Through Ajax</h2>
<table id="userTable" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </tfoot>
    </table>
 <script>
 $(document).ready(function() {
                $(document).ready(function() {
                    $('#userTable').dataTable( {
                        "ajax": "<%=usersArrayURL%>"
                    } );
                } );
            } );
 </script>


Portlet Serve Resource Code

public void arrayOfJSONUserData(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws IOException,
PortletException {
JSONArray allUsersJsonArray = JSONFactoryUtil.createJSONArray();
try {
logger.info("====serveResource========");
JSONArray jsonUserArray = null;

List<User> userList = UserLocalServiceUtil.getUsers(1,UserLocalServiceUtil.getUsersCount());
for (User userObj : userList) {
jsonUserArray = JSONFactoryUtil.createJSONArray();
jsonUserArray.put(userObj.getUserId());
jsonUserArray.put( userObj.getScreenName());
jsonUserArray.put(userObj.getFirstName());
jsonUserArray.put(userObj.getLastName());
jsonUserArray.put(userObj.getEmailAddress());
jsonUserArray.put(userObj.getJobTitle());
allUsersJsonArray.put(jsonUserArray);
}
} catch (Exception e) {
e.printStackTrace();
}
JSONObject tableData = JSONFactoryUtil.createJSONObject();
tableData.put("data", allUsersJsonArray);
logger.info("tableData:"+tableData.toString());
ServletResponseUtil.write(PortalUtil.getHttpServletResponse(resourceResponse),
tableData.toString());
}


Load Data Using Ajax as Flat Data


JSP Page

<%@page import="com.liferay.portal.model.User"%>
<%@page import="com.liferay.portal.service.UserLocalServiceUtil"%>
<%@include file="init.jsp" %>
<script src="<%=renderRequest.getContextPath()%>/js/jquery-1.11.1.min.js"></script>
<script src="<%=renderRequest.getContextPath()%>/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="<%=renderRequest.getContextPath()%>/css/jquery.dataTables.css">
<portlet:resourceURL var="usersFlatDataSourceURL">
            <portlet:param name="cmd" value="flatDataSource"/>
</portlet:resourceURL>
<style>
.message-container{
 padding:10px;
 margin:2px;
 display:none;
 background: rgba(128, 128, 128, 0.33);
 border: 1px solid #0A0A0C;
 }
</style>
<h2>Jquery Data Table with Flat Array Of Ojbects from Server Through Ajax</h2>
<table id="userTable" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </tfoot>
    </table>
 <script>
 $(document).ready(function() {
                $('#userTable').dataTable( {
                    "ajax": {
                      "url":"<%=usersFlatDataSourceURL%>",
                      "dataSrc": ""
                     },
                    "columns": [
                        { "data": "userId" },
                        { "data": "screeName" },
                        { "data": "firstName" },
                        { "data": "lastName" },
                        { "data": "email" },
                        { "data": "jobTitle" }
                    ]
                } );
            } );
 </script>


Portlet Serve Resource Code

public void flatDataSource(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws IOException,
PortletException {
JSONArray usersJsonArray = JSONFactoryUtil.createJSONArray();
try {
logger.info("====serveResource========");
JSONObject jsonUser = null;

List<User> userList = UserLocalServiceUtil.getUsers(1,UserLocalServiceUtil.getUsersCount());
for (User userObj : userList) {
jsonUser = JSONFactoryUtil.createJSONObject();
jsonUser.put("userId", userObj.getUserId());
jsonUser.put("screeName", userObj.getScreenName());
jsonUser.put("firstName", userObj.getFirstName());
jsonUser.put("lastName", userObj.getLastName());
jsonUser.put("email", userObj.getEmailAddress());
jsonUser.put("jobTitle", userObj.getJobTitle());
usersJsonArray.put(jsonUser);
}
} catch (Exception e) {
e.printStackTrace();
}

logger.info("tableData:"+usersJsonArray.toString());
ServletResponseUtil.write(PortalUtil.getHttpServletResponse(resourceResponse),
usersJsonArray.toString());
}


Load Data Using Ajax using Custom Property


JSP Page

<%@page import="com.liferay.portal.model.User"%>
<%@page import="com.liferay.portal.service.UserLocalServiceUtil"%>
<%@include file="init.jsp" %>
<script src="<%=renderRequest.getContextPath()%>/js/jquery-1.11.1.min.js"></script>
<script src="<%=renderRequest.getContextPath()%>/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="<%=renderRequest.getContextPath()%>/css/jquery.dataTables.css">
<portlet:resourceURL var="usersCustomDataSourceURL">
            <portlet:param name="cmd" value="customDataProperty"/>
</portlet:resourceURL>
<style>
.message-container{
 padding:10px;
 margin:2px;
 display:none;
 background: rgba(128, 128, 128, 0.33);
 border: 1px solid #0A0A0C;
 }
</style>
<h2>Jquery Data Table with Custom data source property from Server Through Ajax</h2>
<table id="userTable" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </tfoot>
    </table>
 <script>
 $(document).ready(function() {
                $('#userTable').dataTable( {
                    "ajax": {
                      "url":"<%=usersCustomDataSourceURL%>",
                      "dataSrc": "mytabledata"
                     },
                    "columns": [
                        { "data": "userId" },
                        { "data": "screeName" },
                        { "data": "firstName" },
                        { "data": "lastName" },
                        { "data": "email" },
                        { "data": "jobTitle" }
                    ]
                } );
            } );
 </script>


Portlet Serve Resource Code

public void customDataObjects(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws IOException,
PortletException {
JSONArray usersJsonArray = JSONFactoryUtil.createJSONArray();
try {
logger.info("====serveResource========");
JSONObject jsonUser = null;

List<User> userList
UserLocalServiceUtil.getUsers(1,UserLocalServiceUtil.getUsersCount());
for (User userObj : userList) {
jsonUser = JSONFactoryUtil.createJSONObject();
jsonUser.put("userId", userObj.getUserId());
jsonUser.put("screeName", userObj.getScreenName());
jsonUser.put("firstName", userObj.getFirstName());
jsonUser.put("lastName", userObj.getLastName());
jsonUser.put("email", userObj.getEmailAddress());
jsonUser.put("jobTitle", userObj.getJobTitle());
usersJsonArray.put(jsonUser);
}
} catch (Exception e) {
e.printStackTrace();
}

JSONObject tableData = JSONFactoryUtil.createJSONObject();
tableData.put("mytabledata", usersJsonArray);
logger.info("tableData:"+tableData.toString());
ServletResponseUtil.write(PortalUtil.getHttpServletResponse(resourceResponse),
tableData.toString());
}
}


Data Table Hidden Columns


JSP

<%@page import="com.liferay.portal.model.User"%>
<%@page import="com.liferay.portal.service.UserLocalServiceUtil"%>
<%@include file="init.jsp" %>
<script src="<%=renderRequest.getContextPath()%>/js/jquery-1.11.1.min.js"></script>
<script src="<%=renderRequest.getContextPath()%>/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="<%=renderRequest.getContextPath()%>/css/jquery.dataTables.css">
<portlet:resourceURL var="usersObjectArrayURL">
            <portlet:param name="cmd" value="jsonUserObjectArray"/>
</portlet:resourceURL>
<style>
.message-container{
 padding:10px;
 margin:2px;
 display:none;
 background: rgba(128, 128, 128, 0.33);
 border: 1px solid #0A0A0C;
 }
</style>
<h2>Jquery Data Table Hidden Columns</h2>
<table id="userTable" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th>User Id</th>
                <th>Screen Name</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email Address</th>
                <th>Job Title</th>
            </tr>
        </tfoot>
    </table>
 <script>
 $(document).ready(function() {
                $('#userTable').dataTable( {
                    "ajax": "<%=usersObjectArrayURL%>",
                    "columns": [
                        { "data": "userId" },
                        { "data": "screeName" },
                        { "data": "firstName" },
                        { "data": "lastName" },
                        { "data": "email" },
                        { "data": "jobTitle" }
                    ],
                    "columnDefs": [
                                   {
                                       "targets": [ 0 ],
                                       "visible": false,
                                       "searchable": false
                                   },
                                   {
                                       "targets": [ 5 ],
                                       "visible": false
                                   }
                               ]
                } );
            } );
 </script>

Portlet Serve Resource Code

public void arrayOfJSONUserObjects(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws IOException,
PortletException {
JSONArray usersJsonArray = JSONFactoryUtil.createJSONArray();
try {
logger.info("====serveResource========");
JSONObject jsonUser = null;

List<User> userList
UserLocalServiceUtil.getUsers(1,UserLocalServiceUtil.getUsersCount());
for (User userObj : userList) {
jsonUser = JSONFactoryUtil.createJSONObject();
jsonUser.put("userId", userObj.getUserId());
jsonUser.put("screeName", userObj.getScreenName());
jsonUser.put("firstName", userObj.getFirstName());
jsonUser.put("lastName", userObj.getLastName());
jsonUser.put("email", userObj.getEmailAddress());
jsonUser.put("jobTitle", userObj.getJobTitle());
usersJsonArray.put(jsonUser);
}
} catch (Exception e) {
e.printStackTrace();
}

JSONObject tableData = JSONFactoryUtil.createJSONObject();
tableData.put("data", usersJsonArray);
logger.info("tableData:"+tableData.toString());
ServletResponseUtil.write(PortalUtil.getHttpServletResponse(resourceResponse),
tableData.toString());
}


Portlet Screens

Screen: 1


Screen: 2



Screen: 3



Author

0 comments :

Post a Comment

Recent Posts

Recent Posts Widget

Popular Posts