Tuesday, October 31, 2017

Read SharePoint list Items using REST API and ReactJS

Read SharePoint list Items using REST API and ReactJS

Step1: Create a "ReactDemo" list and list columns as shown below.

Step2: Create an HTML page and saved as "react.html" and upload into Site Assets library in SharePoint. Copy the "react.html" file full url from for future reference. Update below in "react.html" file.

react.html:
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@15.3.2/dist/react.js"></script>
  <script src="https://unpkg.com/react-dom@15.3.2/dist/react-dom.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<style></style>
</head>
<body>
  <div id="container"></div> 
  <script type="text/babel">
    var destination = document.querySelector("#container");
    class LinksClass extends React.Component {
        debugger;
        constructor() {
            super();
            this.state = {
                Links: [
                    {
                        "Link_x0020_Title": "",
                        "Title": ""
                    }
                ]
            };
        }
        componentDidMount() {
            debugger;
            this.RetrieveLinksData();
        }
        RetrieveLinksData() {
            var reactHandler = this;
            var objHeaders = {
                type: "GET",
                headers: {
                    "accept": "application/json;odata=verbose"
                },
                mode: 'cors',
                cache: 'default',
                credentials: 'include'
            }
            fetch("https://sharepointonline01.sharepoint.com/sites/dev/_api/web/lists/getbytitle('ReactDemo')/items",
                objHeaders).then(function (response) {
                return response.json()
            })
            .then(function (json) {
                var results = json.d.results;
                reactHandler.setState({Links: results});    
            })
            .catch(function (ex) {
                console.log('parsing failed', ex)
            })
        }
        render() {
            debugger;
            return (
                <div>
                    <h4>Links</h4>
                    <ul>
                        {this
                            .state
                            .Links
                            .map(function (item, key) {
                                return (
                                    <li key={key}>
                                        <a href={item.Link_x0020_Title.Url}>
                                            {item.Title}
                                        </a>
                                    </li>
                                );
                            })
                          }
                    </ul>
                </div>                  
            );
        }
    }
    ReactDOM.render(
      <LinksClass/>,
      document.getElementById('container')
    );
</script>
</body>
</html>


Step3: Create a webpart page and add content editor webpart in to the page. update content link url with "react.html" page url.

Step4: final result.

Sunday, September 24, 2017

CRUD operation in SharePoint Online using REST, AngularJS

CRUD operation in SharePoint Online using REST, AngularJS
Step 1:-
---------------------
Create custom list as "Employees"

Step 2:-
---------------------
Create Folder structure as below format.

Use below images for edit, delete, cancel buttons.


Step 3:-
---------------------
Update below code.
style.css:-
---------------------
.all-employees table{
       font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    width: 100%;
    border-collapse: collapse;
    border: 1px solid #999999;
} 
.all-employees table th{
       font-size: 1.4em;
  text-align: left;
  padding: 5px;
  text-align: center;
  border-right: 1px solid #999999;
} 
.all-employees table td{
  font-size: 1.2em;
  border: 1px solid #999999;
  padding: 5px;
  text-align: center;
}
.all-employees{
  margin-top: 17px;
}
.add-new-button{
  background-color: rgb(55, 139, 202);
  padding: 8px;
  color: white;
}
.add-new-button:visited{
  color: white;
}
.employees-app{
   width: 800px;
}
.employees-app-table{
  width: 100%;
}
.employees-app-table input[type=text], textarea{
  width: 50%!important;
}
.employees-app-table input[type=button]{
  margin: 0!important;
}
add.js:-
---------------------
"use strict";
(function () {
       angular.module("EmployeesApp")
              .controller("addEmployeeCtrl", ["$scope", "employeesService","$location",
              function ($scope, employeesService,$location) {
              $scope.addEmployee = function (employee) {
                     employeesService.addNew(employee)
                     .then(function(response){
                           console.log(response);
                           $location.path("/");
                     });
                    
              };
       }]);
})();
all.js:-
---------------------
"use strict";
(function () {
       angular.module("EmployeesApp")
              .controller("allEmployeesCtrl", ["$scope", "employeesService",
              function ($scope, employeesService) {
                     employeesService.getAll()
                           .then(function (response) {
                $scope.employees = response.d.results;
                     });
                     $scope.removeEmployee = function(employee){                  
                           if (confirm(" Are you sure want to delete " + employee.FirstName + " " + employee.LastName + " ?")) {       
                                  employeesService.remove(employee.ID)
                                  .then(function(response){
                                         var employeeIndex = $scope.employees.indexOf(employee);
                                         $scope.employees.splice(employeeIndex,1);
                                  });
                           }
                     };
              }]);
})();
cancel.js:-
---------------------
"use strict";
(function () {
       angular.module("EmployeesApp")
              .controller("cancelEditEmployeeCtrl", ["$scope", "employeesService",
              function ($scope, employeesService) {
                     employeesService.cancelRequest()
                           .then(function (response) {
                $scope.employees = response.d.results;
                     });
                     $scope.removeEmployee = function(employee){
                           employeesService.remove(employee.ID)
                           .then(function(response){
                                  var employeeIndex = $scope.employees.indexOf(employee);
                                  $scope.employees.splice(employeeIndex,1);
                           });
                     };
              }]);
})();
edit.js:-
---------------------
"use strict";
(function () {
       angular.module("EmployeesApp")
              .controller("editEmployeeCtrl", ["$scope", "employeesService", "$routeParams","$location",
                     function ($scope, employeesService, $routeParams,$location) {
                           employeesService.getById($routeParams.employeeId)
                                  .then(function (response) {
                                         $scope.employee = {
                                                employeeId : response.d.ID,
                                                firstName: response.d.FirstName,
                                                lastName: response.d.LastName
                                         };
                                         $scope.editEmployee = function(employee){
                                                employeesService.update(employee)
                                                .then(function(response){
                                                       $location.path("/");
                                                });
                                         };
                                  });
                     }]);
})();
employees.js:-
---------------------
"use strict";
(function(){
       angular.module("EmployeesApp")
       .factory("employeesService",["baseSvc",function(baseService){
              var listEndPoint = '/_api/web/lists';
              var getAll = function(){
                     var query = listEndPoint + "/GetByTitle('Employees')/Items?$select=ID,FirstName,LastName";
                     return baseService.getRequest(query);
              };
              var addNew = function(employee){
                     var data = {
                           __metadata: { 'type': 'SP.Data.EmployeesListItem' },
                           FirstName : employee.firstName,
                           LastName : employee.lastName
                     };
                     var url = listEndPoint + "/GetByTitle('Employees')/Items";
                     return baseService.postRequest(data,url);
              };
              var getById = function(employeeId){
                     var query = listEndPoint + "/GetByTitle('Employees')/GetItemById("+employeeId+")?$select=ID,FirstName,LastName";
                     return baseService.getRequest(query);
              };
              var update = function (employee){
                     var data = {
                           __metadata: { 'type': 'SP.Data.EmployeesListItem' },
                           FirstName : employee.firstName,
                           LastName : employee.lastName
                     };
                     var url = listEndPoint + "/GetByTitle('Employees')/GetItemById("+employee.employeeId+")";
                     return baseService.updateRequest(data,url);
              };
              var remove = function(employeeId){
                     var url = listEndPoint + "/GetByTitle('Employees')/GetItemById("+employeeId+")";
                     return baseService.deleteRequest(url);
              };
              var cancel = function(){
                     var query = listEndPoint + "/GetByTitle('Employees')/Items?$select=ID,FirstName,LastName";
                     return baseService.cancelRequest(query);
              };
              return{
                     getAll:getAll,
                     addNew:addNew,
                     getById:getById,
                     update:update,
                     remove:remove,
                     cancel:cancel
              };
       }]);
})();
baseSvc.js:-
---------------------
"use strict";
(function () {
    angular.module("EmployeesApp")
        .factory("baseSvc", ["$http", "$q", function ($http, $q) {
        var baseUrl = _spPageContextInfo.webAbsoluteUrl;
        var getRequest = function (query) {
            var deferred = $q.defer();
            $http({
                url: baseUrl + query,
                method: "GET",
                headers: {
                    "accept": "application/json;odata=verbose",
                    "content-Type": "application/json;odata=verbose"
                }
            })
                .success(function (result) {
                deferred.resolve(result);
            })
                .error(function (result, status) {
                deferred.reject(status);
            });
            return deferred.promise;
        };
        var postRequest = function (data, url) {
            var deferred = $q.defer();
            $http({
                url: baseUrl + url,
                method: "POST",
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
                    "content-Type": "application/json;odata=verbose"
                },
                data: JSON.stringify(data)
            })
                .success(function (result) {
                deferred.resolve(result);
            })
                .error(function (result, status) {
                deferred.reject(status);
            });
            return deferred.promise;
        };
        var updateRequest = function (data, url) {
            var deferred = $q.defer();
            $http({
                url: baseUrl + url,
                method: "PATCH",
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value,
                    "content-Type": "application/json;odata=verbose",
                    "X-Http-Method": "PATCH",
                    "If-Match": "*"
                },
                data: JSON.stringify(data)
            })
                .success(function (result) {
                deferred.resolve(result);
            })
                .error(function (result, status) {
                deferred.reject(status);
            });
            return deferred.promise;
        };
        var deleteRequest = function(url){
            var deferred = $q.defer();
            $http({
                url: baseUrl + url,
                method: "DELETE",
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest":document.getElementById("__REQUESTDIGEST").value,
                    "IF-MATCH": "*"
                }
            })
                .success(function (result) {
                    deferred.resolve(result);
                })
                .error(function (result, status) {
                    deferred.reject(status);
                });
            return deferred.promise;
         };
         var cancelRequest = function (query) {
            var deferred = $q.defer();
            $http({
                url: baseUrl + query,
                method: "GET",
                headers: {
                    "accept": "application/json;odata=verbose",
                    "content-Type": "application/json;odata=verbose"
                }
            })
                .success(function (result) {
                deferred.resolve(result);
            })
                .error(function (result, status) {
                deferred.reject(status);
            });
            return deferred.promise;
        };
        return {
            getRequest: getRequest,
            postRequest: postRequest,
            updateRequest: updateRequest,
            deleteRequest:deleteRequest,
            cancelRequest:cancelRequest
        };
    }]);
})();
app.js:-
---------------------
"use strict";
(function () {
       angular.module("EmployeesApp", ["ngRoute"])
              .config(["$routeProvider", function ($routeProvider) {
              $routeProvider.when("/", {
                     templateUrl: "/sites/dev/SiteAssets/employees01/templates/employees/all.html",
                     controller: "allEmployeesCtrl"
              }).when("/addEmployee", {
                     templateUrl: "/sites/dev/SiteAssets/employees01/templates/employees/add.html",
                     controller: "addEmployeeCtrl"
              }).when("/editEmployee/:employeeId", {
                     templateUrl: "/sites/dev/SiteAssets/employees01/templates/employees/edit.html",
                     controller: "editEmployeeCtrl"
              }).when("/cancelEditEmployee/:employeeId", {
                     templateUrl: "/sites/dev/SiteAssets/employees01/templates/employees/edit.html",
                     controller: "cancelEditEmployeeCtrl"
              });
       }]);
})();
add.html:-
---------------------
<h2>Add New</h2>
<hr>
<table class="employees-app-table">
       <tr>
              <td>First Name</td>
              <td>
                     <input type="text" data-ng-model="employee.firstName">
              </td>
       </tr>
       <tr>
              <td>Last Name</td>
              <td>
                     <input type="text" data-ng-model="employee.lastName">
              </td>
       </tr> 
       <tr>
              <td></td>
              <td>
                     <input type="image" src="/sites/dev/SiteAssets/employees01/images/save.png" alt="Save" data-ng-click="addEmployee(employee)">
                     <input type="image" src="/sites/dev/SiteAssets/employees01/images/cancel.png" alt="Cancel" data-ng-click="cancelEditEmployee(employee)">
              </td>
       </tr>
</table>
all.html:-
---------------------
<div class="all-employees">
       <table>
              <tbody>
                     <tr>
                           <th>First Name</th>
                           <th>Last Name</th>
                           <th>Action</th>
                     </tr>
                     <tr data-ng-repeat="employee in employees">
                           <td>{{employee.FirstName}}</td>
                           <td>{{employee.LastName}}</td>
                           <td>
                                  <a href="#/editEmployee/{{employee.ID}}"><img src="/sites/dev/SiteAssets/employees01/images/edit.png" alt="Edit"></a>
                                  <a href="" data-ng-click="removeEmployee(employee)"><img src="/sites/dev/SiteAssets/employees01/images/delete.png" alt="Delete"></a>
                           </td>
                     </tr>
              </tbody>
       </table>
</div>
<a href="#/addEmployee" class="add-new-button">Add New Employee</a>
edit.html:-
---------------------
<h2>Edit</h2>
<hr>
<table class="employees-app-table">
       <tr>
              <td>First Name</td>
              <td><input type="text" data-ng-model="employee.firstName"></td>
       </tr>
       <tr>
              <td>Last Name</td>
              <td><input type="text" data-ng-model="employee.lastName"></td>
       </tr>
       <tr>
              <td></td>
               <td>
                     <input type="image" src="/sites/dev/SiteAssets/employees01/images/save.png" alt="Save" data-ng-click="editEmployee(employee)">
                     <input type="image" src="/sites/dev/SiteAssets/employees01/images/cancel.png" alt="Cancel" data-ng-click="cancelEditEmployee(employee)">
               </td>
       </tr>
</table>

Employees.txt:-
---------------------
<link href="/sites/dev/SiteAssets/employees01/css/style.css" rel="stylesheet" type="text/css">
<script src="/sites/dev/SiteAssets/employees01/lib/angular.min.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/lib/angular-route.min.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/js/app.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/js/services/baseSvc.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/js/services/employees/employees.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/js/controllers/employees/all.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/js/controllers/employees/add.js" type="text/javascript"></script>
<script src="/sites/dev/SiteAssets/employees01/js/controllers/employees/edit.js" type="text/javascript"></script>
<div data-ng-app="EmployeesApp">
       <div data-ng-view class="employees-app"></div>
</div>

Step 4:-
---------------------
Upload these files into Site Assets.
Step 5:-
---------------------
Create a page and add Content Editor Webpart and 

Step 6:-
---------------------
Test the application.