Tuesday, January 10, 2017

Tasks List with PNP JS & DataTable in SharePoint

Hi ,

I have created one example for SharePoint with pnp-js & datatable. 
Features which I have covered in this example :
  • Open task display page in new tab.
  • Show Priorities in different colors.
  • Show Percent Completed as Progress Bar
  • Show dates in proper formats.
  • Show Assigned To (Multi-people)


Here is the code :

You need to add following references :
<script src="https://code.jquery.com/jquery-2.2.0.min.js" integrity="sha256-ihAoc6M/JPfrIiIeayPE9xjin4UWjsx2mjW/rtmxLM4=" crossorigin="anonymous"></script>

<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" charset="utf8" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>

<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/plug-ins/1.10.12/sorting/datetime-moment.js"></script>

You need to download following files & add the reference :
 <script type="text/javascript" charset="utf8" src="/sites/MyDev/Style%20Library/SPS/pnp.js"></script>
<script type="text/javascript" charset="utf8" src="/sites/MyDev/Style%20Library/SPS/es6-promise.min.js"></script>
<script type="text/javascript" charset="utf8" src="/sites/MyDev/Style%20Library/SPS/fetch.js"></script>

Now you need to create HTML table with required columns :

<table width="100%" cellpadding="0" cellspacing="0" border="0" class="display" id="exampleTask">
    <thead>
    <th>Task Name</th>
    <th>Due Date</th>
    <th>Assigned To</th>
    <th>Priority</th>
    <th>Start Date</th>
    <th>Task Status</th>
    <th>Progress</th>
    </thead>

</table>


 This is the function which fill the data & format the datatable :
function LoadTaskItems()
{
        $pnp.setup({
            headers: {
                "Accept" : "application/json; odata=verbose",
            },
        });
        var baseUrl=_spPageContextInfo.siteAbsoluteUrl;
        var MyWeb = new $pnp.Web(baseUrl);
        //$pnp.sp.web.lists.getByTitle('Tasks').items.expand('AssignedTo').select('ContentTypeId,Title,Priority,Status,PercentComplete,AssignedTo/ID,AssignedTo/Title,StartDate,DueDate,ParentID,ID,Modified,Created,Author,Editor,FileDirRef').orderBy('ID').get().then(function (response) {
        MyWeb.lists.getByTitle('Tasks').items.expand('AssignedTo').select('ContentTypeId,Title,Priority,Status,PercentComplete,StartDate,DueDate,ID,Modified,Created,AssignedTo/ID,AssignedTo/Title,FileDirRef').orderBy('ID').get().then(function (response) {
            //alert(JSON.stringify( response[0].AssignedTo.results[0].Title));
            var generateCustomerTable = $("#exampleTask")
            .dataTable({
              "aaData": response,
              "processing": true,
              "autoWidth": true,
              "bDestroy": true,
              "aoColumns": [
                { "mData": "Title",  "width": "20%","fnCreatedCell" :
                    function (nTd, sData, oData, iRow, iCol)
                    {
                        $(nTd).html("<a href='"+ oData.FileDirRef +"/DispForm.aspx?ID="+oData.ID+"' target='_blank'>"+oData.Title+"</a>");
                    }
                },
                { "data": "DueDate", "stype": "date",
                    "render": function( data, type, row, meta){
                            var ThisDate = moment(new Date(data)).format("Do MMM YYYY");
                            return ThisDate
                    }
                },
                { "data": "AssignedTo.results[, ].Title"

                },
                { "data": "Priority" ,"fnCreatedCell" :
                    function (nTd, sData, oData, iRow, iCol)
                    {
                        var displayValue='';
                        switch (oData.Priority) {
                            case "(1) High":
                                displayValue="<span style='color :#f00'>" + oData.Priority + "</span>";
                                break;
                            case "(2) Normal":
                                displayValue="<span style='color :#ff6a00'>" + oData.Priority + "</span>";
                                break;
                            case "(3) Low":
                                displayValue="<span style='color :#cab023'>" + oData.Priority + "</span>";
                        }
                        $(nTd).html(displayValue);
                    }
                },
                { "data": "StartDate" , "stype": "date",
                    "render": function( data, type, row, meta){
                            var ThisDate = moment(new Date(data)).format("Do MMM YYYY");
                            return ThisDate
                    }
                },
                { "data": "Status"
                },
                { "data": "PercentComplete","width": "150px;" ,"fnCreatedCell" :
                    function (nTd, sData, oData, iRow, iCol)
                    {
                        var val= ((oData.PercentComplete * 100));
                        var tt= "<div style='background-color: #e5e5e5; width: 100px;  display:inline-block;'><div style='width: " + val + "px; background-color: #0094ff;'>&nbsp;</div></div>&nbsp;" + (oData.PercentComplete * 100);
                        $(nTd).html(tt);
                    }

                }
              ],
              "language": {
                "emptyTable": "There are no tasks at present.",
                "zeroRecords": "There were no matching tasks found."
              },
              "caseInsensitive": false,
              "searching": true,
              "pageLength": 50,
              "ordering": true,
              "paging": true,
              "order": [0, "asc"],
            });
        });

}

Wednesday, November 30, 2016

Organization Chart with AngularJS



What is Organization Chart?

An Organizational Chart shows the internal structure of an organization or company. The employees and positions are represented by boxes or other shapes, sometimes including photos, contact information, email and page links, icons and illustrations. Straight or elbowed lines link the levels together.  This creates a clear visual depiction of the hierarchy and ranks of different people, jobs and departments that make up the organization.
Organizational Charts also are known as Organization Charts, Org Charts, Organograms, Organogram Charts (sometimes spelled Organigrams or Organigrammes) and Hierarchy Charts. Don’t be fooled: Despite all the different names, they’re all the same thing.

How to create with angularjs & google chart?

First you need to create one JS file: OrgChart.JS & copy below text :
var app = angular.module('OrgChartApp', []);
app.controller('OrgChartController', ['$scope', '$http', function ($scope, $http) {
    //here http get method for get data from database
    $scope.chartData = [['Name', 'ReportsTo', 'JobTitle']];
    var data = [{ ID: 1, EmployeeName: 'Gaurav Goyal', Title: 'Product Archtech', ReportsTo: 0, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' },
        { ID: 2, EmployeeName: 'David Verti', Title: 'SSE', ReportsTo: 1, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' },
        { ID: 3, EmployeeName: 'Rahul Khanna', Title: 'SSE', ReportsTo: 1, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' },
        { ID: 4, EmployeeName: 'Tarun Sharma', Title: 'SE', ReportsTo: 2, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' },
        { ID: 5, EmployeeName: 'Yaman Raj', Title: 'SE', ReportsTo: 2, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' },
        { ID: 6, EmployeeName: 'Sanjay Jain', Title: 'SE', ReportsTo: 3, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' },
        { ID: 7, EmployeeName: 'Om Prakash', Title: 'SE', ReportsTo: 3, img_url: '//lh5.googleusercontent.com/-evpjmrDWNMQ/AAAAAAAAAAI/AAAAAAAAAcY/d7qvMNmJlNw/s80-c/photo.jpg' }
    ];

    var newobject = [['Name', 'ReportsTo', 'JobTitle']];
    angular.forEach(data, function (val) {
        newobject.push(
            [
                {
                    v: val.ID.toString(),
                    f: '<div class="parent">'
                        + '<div> '
                        + '<img src="' + val.img_url + '" class="iconDetails">'
                        + ' </div>'
                        + ' <div class="text">'
                        + '<h4><b>' + val.EmployeeName + '</b></h4>'
                        + '<div >' + val.Title + '</div>'
                        + '<div >gauravgoyal_5@yahoo.com</div>'
                        + '</div>'
                        + '</div>'
                },
                (val.ReportsTo.toString() === "0" ? "" : val.ReportsTo.toString()),
                (val.EmployeeName)
            ]
            );

    })
    $scope.chartData = newobject;

}])
app.directive('orgChart', function () {
    function link($scope, element, attrs) {
        var chart = new google.visualization.OrgChart(element[0]);
        $scope.$watch('chartData', function (value, oldvalue) {
            if (!value) {
                return;
            }
            var data = google.visualization.arrayToDataTable(value);
            var options = {
                'title': '',
                'allowHtml': true
            }
            chart.draw(data, options);
        })
    }
    return {
        link: link
    };
})

Now you need to create HTML file :  OrgChart.html & copy below text :
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart','orgchart']}]}"></script>
<script src="//SiteAssets/OrgChart-3.js"></script>
    <style>
        .iconDetails {
   float: left;
    height: 75px;
       width: 75px;
   padding:10px;
  }
.parent{
      
    display:table;
    width:300px;
      
}
.text{
display: table;
text-align:left;
}

        .google-visualization-orgchart-node-medium {
            width: 200px;
        }

        .ms-rtestate-field h4, h4.ms-rteElement-H4 {
            font-size: 1.3em;
            color: brown;
            padding-top:10px;
            padding-left:0px;
            margin-left:0px;
        }

        .google-visualization-orgchart-node {
            background: transparent;
        }
    </style>

</head>

<body ng-app="OrgChartApp">
    <div ng-controller="OrgChartController">
                <div id="chart" ng-model="chartData" org-chart="chartData" style="text-align:center">
           
        </div>
    </div>
</body>
</html>






Here is final outcome :