Sunday, February 25, 2018

DataTable Custom Paging using REST in SharePoint

DataTable Custom Paging using REST in SharePoint.
1. Create 'Employee' list and add some data.
2. Create a script file and add into Site Assets library.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>  
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"/>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"/>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>       
    <script type="text/javascript">
        var paginateMaxID = "";
        var paginateMinID = "";
        var paginateNext = "Next";
        var paginatePrevious = "Previous";
        var paginateCountPerPage = 3;
        var lstEmployee = 'Employees';      
        $(document).ready(function(){
            GetEmployeeItems(); 
            $("#liPrevious").click(function() {
                DataTablePaginate($("#liPrevious").text().trim());
            });
            $("#liNext").click(function() {
                DataTablePaginate($("#liNext").text().trim());
            }); 
            $("#divPaginationPager").show();
        });
        function GetEmployeeItems(pPreviousOrNext) {
            var url = "";
            var response =  [];     
            if(pPreviousOrNext == undefined) {
                url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('"+lstEmployee+"')/items?$top="+paginateCountPerPage+
                    "&$select=ID,Title,Address&$orderby=ID desc";       
            } else if(pPreviousOrNext==paginateNext) {
                url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('"+lstEmployee+"')/items?"+
                    "$filter=ID gt "+paginateMaxID+"&$top="+paginateCountPerPage+"&$select=ID,Title,Address&$orderby=ID asc";       
            } else if(pPreviousOrNext==paginatePrevious) {
                url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('"+lstEmployee+"')/items?"+
                    "$filter=ID lt "+paginateMinID+"&$top="+paginateCountPerPage+"&$select=ID,Title,Address&$orderby=ID desc";  
            }           
            $.ajax({
                url: url,
                type: "GET",
                headers:
                    Accept: "application/json;odata=verbose" 
                }, 
                async: false,
                cache: false,
                beforeSend: function(){ 
                },
                success: function (data, status, xhr) {
                    if(data.d.results != undefined && data.d.results.length > 0) {
                        response = data.d.results;
                    }           
                    $('#divDataTablePagingEmployee').html("");
                    $('#tblDataTablePagingEmployee').html("");
                    if (response != undefined && response.length > 0) {
                        $('#divDataTablePagingEmployee').append(getDatatable(response,pPreviousOrNext));
                    } else {                        
                         var tableContent =
                            '<table id="tblDataTablePagingEmployee" class="table table-striped table-bordered" cellspacing="0" width="100%">'+
                                '<thead>'+
                                    '<tr>'+
                                        '<th class="bg-primary" style="text-align: center; !important">ID</th>'+
                                        '<th class="bg-primary" style="text-align: center; !important">Name</th>'+
                                        '<th class="bg-primary" style="text-align: center; !important">Address</th>'+
                                    '</tr>'+
                                '</thead>'+
                                '<tbody>';
                        tableContent += '<tr>';
                        tableContent += '<td><span>No records found</span></td><td></td><td></td>';
                        tableContent += '</tr>';      
                        tableContent +='</tbody></table>';
                        $('#divDataTablePagingEmployee').append(tableContent);  
                        console.log("no records found");
                    }                       
                    if(!$.fn.DataTable.isDataTable('#tblDataTablePagingEmployee')) {                    
                        var table = $('#tblDataTablePagingEmployee').DataTable({
                            "columnDefs": [{"className": "dt-center", "targets": "_all"}],
                            "pagingType": "simple",
                            "lengthMenu": [[5000, -1], [5000, "All"]],
                            "ordering": false,
                            "order": []                         
                        });
                    }           
                    if($("#tblDataTablePagingEmployee_length").length>0) {
                        $("#tblDataTablePagingEmployee_length").hide();
                    }
                    if($("#tblDataTablePagingEmployee_paginate").length>0) {
                        $("#tblDataTablePagingEmployee_paginate").hide();
                    }
                    if($("#tblDataTablePagingEmployee_info").length>0) {
                        $("#tblDataTablePagingEmployee_info").hide();
                    }
                    if (!(response != undefined && response.length > 0)) {
                        if(pPreviousOrNext==paginateNext) {
                            paginateMinID = paginateMaxID+1;
                            paginateMaxID = "";                     
                            var addClassNextDisabled = $("#liNext").attr('class');
                            if(addClassNextDisabled.indexOf("disabled")<0) { 
                                $("#liNext").addClass("disabled");
                            }                       
                        } else if(pPreviousOrNext==paginatePrevious) {
                            paginateMaxID = paginateMinID-1;
                            paginateMinID= "";
                            var addClassPreviousDisabled = $("#liPrevious").attr('class');
                            if(addClassPreviousDisabled.indexOf("disabled")<0) { 
                                $("#liPrevious").addClass("disabled");
                            }                       
                        }
                    }                   
                },
                error: function (xhr, status, error) {
                    $("#divdanger").text("error: " + xhr.responseText);
                    $("#divdanger").show();       
                },
                complete: function() {
                    if($('#divDataTablePagingEmployee').html()=="") {
                        $('#divDataTablePagingEmployee').append("<span>Item does not exist. It may have been deleted by another user. </span>");
                    }
                } 
            });
        }
        function getDatatable(listData,pPreviousOrNext) {   
            paginateMaxID = "";
            paginateMinID = ""
            var tableContent =
            '<table id="tblDataTablePagingEmployee" class="table table-striped table-bordered" cellspacing="0" width="100%">'+
                '<thead>'+
                    '<tr>'+
                        '<th class="bg-primary" style="text-align: center; !important">ID</th>'+
                        '<th class="bg-primary" style="text-align: center; !important">Name</th>'+
                        '<th class="bg-primary" style="text-align: center; !important">Address</th>'+
                    '</tr>'+
                '</thead>'+
                '<tbody>';  
            if(pPreviousOrNext==paginateNext) {
                listData.reverse();
            }       
            for (var i = 0; i < listData.length; i++) {
                if(i == 0) {
                    paginateMaxID = listData[i]["ID"];
                }
                if(i == listData.length-1) {
                    paginateMinID = listData[i]["ID"];
                }                            
                tableContent += '<tr>';
                tableContent += '<td>'+(listData[i]["ID"]!=null&&listData[i]["ID"]!=""?listData[i]["ID"]:"")+'</td>';
                tableContent += '<td>'+(listData[i]["Title"]!=null&&listData[i]["Title"]!=""?listData[i]["Title"]:"")+'</td>';
                tableContent += '<td>'+(listData[i]["Address"]!=null&&listData[i]["Address"]!=""?listData[i]["Address"]:"")+'</td>';
                tableContent += '</tr>';       
            }
            tableContent +='</tbody></table>';   
            return tableContent;
            console.log(tableContent);
        }
        function DataTablePaginate(pPreviousOrNext) {   
            if(pPreviousOrNext == paginateNext) {
                var clsPreviousDisabled = $("#liPrevious").attr('class');
                if(clsPreviousDisabled.indexOf("disabled")>0) { 
                    $("#liPrevious").removeClass("disabled");
                }       
            }
            if(pPreviousOrNext == paginatePrevious) {
                var clsNextDisabled = $("#liNext").attr('class');
                if(clsNextDisabled.indexOf("disabled")>0) { 
                    $("#liNext").removeClass("disabled");
                }
            }                   
            if(($("#liPrevious").attr('class').indexOf("disabled")<0 && pPreviousOrNext == paginatePrevious) ||
               ($("#liNext").attr('class').indexOf("disabled")<0 && pPreviousOrNext == paginateNext)) {
                GetEmployeeItems(pPreviousOrNext);
            }   
        }
    </script>   
</head>
<body>
<p class="h1">DataTable Custom Paging using REST in SharePoint</p>
<div id="divDataTablePagingEmployee"></div>
<div id="divPaginationPager" class="row" style="display:none;">
    <div class="col-lg-10 col-md-10 col-sm-10 col-xs-10"></div>
    <div  class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
          <ul class='pagination'>
            <li class='page-item' id='liPrevious'>
              <a class='page-link' href='#' tabindex='-1'>Previous</a>
            </li>
            <li class='page-item disabled' id='liNext'>
              <a class='page-link' href='#'>Next</a>
            </li>
          </ul>
    </div>
</div>
</body>
</html>

3. Add 'Content Editor' webpart into a page and give content link as above script file url from Site Assets.

4. Check the result.

No comments:

Post a Comment