Search This Blog

Monday, January 14, 2019

SharePoint - Load People Picker field And insert/Update custom List using Javascript/AngularJS



step1: Create custom List and column as per below screen shot



step2 : Choose Allow-multiple true and allow People and Groups option

and copy paste below script in script editor. Note : you can create separate script and refer your page like.. constant.js and baseSvc.js like that


<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script src="/_layouts/15/clientpeoplepicker.js"></script>
    <script src="/_layouts/15/clienttemplates.js"></script>
    <script src="/_layouts/15/clientforms.js"></script>
    <script src="/_layouts/15/sp.runtime.js"></script>
    <script src="/_layouts/15/autofill.js"></script>
    <script src="/_layouts/15/sp.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.min.js"></script>
    <script>
        var app = angular.module('testApp', []);
        var Utility = Utility || {};
        Utility.helpers = {
            initializePeoplePicker: function (peoplePickerElementId) {
                // Create a schema to store picker properties, and set the properties.
                var schema = {};
                schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
                schema['SearchPrincipalSource'] = 15;
                schema['ResolvePrincipalSource'] = 15;
                schema['AllowMultipleValues'] = true;
                schema['MaximumEntitySuggestions'] = 50;
                schema['Width'] = '280px';
                // Render and initialize the picker.
                // Pass the ID of the DOM element that contains the picker, an array of initial
                // PickerEntity objects to set the picker value, and a schema that defines
                // picker properties.
                SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
            },
            getUserInfo: function (peoplePickerElementId) {
                var UsersID = "";
                var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerElementId + "_TopSpan"];

                if (peoplePicker.HasInputError) return false; // if any error
                else if (!peoplePicker.HasResolvedUsers()) return false; // if any invalid users
                else if (peoplePicker.TotalUserCount > 0) {
                    // Get information about all users.
                    var users = peoplePicker.GetAllUserInfo();
                    //var userInfo = '';
                    //var promise = '';
                    for (var i = 0; i < users.length; i++) {
                        UsersID += users[i].DisplayText + "\n";
                        UsersID += users[i].EntityData.Email;
                    }
                    // Get user keys.
                    var keys = peoplePicker.GetAllUserKeys();
                    var finalusers = new Array();
                    for (var i = 0; i < users.length; i++) {
                        var arryuser = users[i];
                        finalusers.push(SP.FieldUserValue.fromUser(arryuser.Key));
                    }
                    return finalusers;
                }
            },
            getUrlParameter: function (name) {
                name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
                var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
                var results = regex.exec(location.search);
                return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
            },
            SetUserFieldValue: function (fieldName, LoginName) {

                var _PeoplePicker = $("div[title='" + fieldName + "']");
                var _PeoplePickerTopId = _PeoplePicker.attr('id');
                var _PeoplePickerEditer = $("input[title='" + fieldName + "']");
                var usrObj = { 'Key': LoginName };
                var _PeoplePickerOject = SPClientPeoplePicker.SPClientPeoplePickerDict[_PeoplePickerTopId + "_TopSpan"];
                _PeoplePickerOject.AddUnresolvedUser(usrObj, true);
                //disable the field
                // _PeoplePickerOject.SetEnabledState(false);
                //hide the delete/remove use image from the people picker
                //  $('.sp-peoplepicker-delImage').css('display', 'none');
            }
        };
app.constant('SharePointList', {
            SystemRequest: 'SystemRequestList'
        });
        app.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"
                    }
                }).then(function (result){
                    deferred.resolve(result);
                },function (error){
                    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)
                }).then(function (result) {
                    deferred.resolve(result);
                }, function (error) {
                    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)
                }).then(function (result) {
                    deferred.resolve(result);
                }, function (error) {
                    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": "*"
                    }
                }).then(function (result) {
                    deferred.resolve(result);
                }, function (error) {
                    deferred.reject(status);
                });
                return deferred.promise;
            };
            return {
                getRequest: getRequest,
                postRequest: postRequest,
                updateRequest: updateRequest,
                deleteRequest: deleteRequest
            };
        }]);
app.factory("peopleService", ["baseSvc", "SharePointList", function (baseService, SharePointList) {
            var listEndPoint = '/_api/web/lists';
            var getAll = function () {
                var query = listEndPoint + "/GetByTitle('" + SharePointList.SystemRequest + "')/Items?$top=1000";
                return baseService.getRequest(query);
            };
            var getById = function (listItemId) {
                var query = listEndPoint + "/GetByTitle('" + SharePointList.SystemRequest + "')/items?$filter=ID eq " + listItemId + "&$select=*"
                            + ",ITManager/EMail,ITManager/Title"
                            + ",DepartmentHead/EMail,DepartmentHead/Title"
                            + ",FinanceManager/EMail,FinanceManager/Title"
                            + ",DirectManager/Title"
                            + "&$expand=ITManager/Id,DepartmentHead/Id,FinanceManager/Id,DirectManager/Id"
                return baseService.getRequest(query);
            };
            var addNew = function (person) {
                var data = {
                    __metadata: { 'type': 'SP.Data.PeopleListItem' },
                    FirstName: person.firstName,
                    LastName: person.lastName,
                    Address: person.address
                };
                var url = listEndPoint + "/GetByTitle('People')/Items";
                return baseService.postRequest(data, url);
            };
            var update = function (person) {
                var data = {
                    __metadata: { 'type': 'SP.Data.PeopleListItem' },
                    FirstName: person.firstName,
                    LastName: person.lastName,
                    Address: person.address
                };
                var url = listEndPoint + "/GetByTitle('People')/GetItemById(" + person.personId + ")";
                return baseService.updateRequest(data, url);
            };
            var remove = function (personId) {
                var url = listEndPoint + "/GetByTitle('People')/GetItemById(" + personId + ")";
                return baseService.deleteRequest(url);
            };
            var getUser = function (id) {
                var url = "/_api/Web/GetUserById(" + id + ")";
                return baseService.getRequest(url);
            }
            var getUserGroup = function (id) {
                var url = "/_api/Web/sitegroups/getById(" + id + ")";
                return baseService.getRequest(url);
            }
            return {
                getAll: getAll,
                addNew: addNew,
                getById: getById,
                update: update,
                remove: remove,
                getUser: getUser,
                getUserGroup: getUserGroup
            };
        }]);
        app.controller('spCustomerController', ["$scope", "$http", "peopleService", function ($scope, $http, peopleService) {
            //sharepoint context
            var ctx = new SP.ClientContext.get_current();
            var web = ctx.get_web();
            //init variable
            $scope.sarProperties = [];
            $scope.sarProperties = ({
                CSCTicketNumber: "",
                RequestType: "",
                FirstName: "",
                LastName: "",
                Telephone: "",
                EmployeePosition: "",
                DirectManager: "",
                Department: "",
                BusinessUnit: "",
                DepartmentHead: "",
                EmployeeNumber: "",
                ITManager: "",
                Status: "Pending",
                FinanceManager: ""
            });
            $scope.listItemId = "";
            $scope.init = function () {
                // Render and initialize the client-side People Picker.
                Utility.helpers.initializePeoplePicker('peoplePickerDirectManager');
                Utility.helpers.initializePeoplePicker('peoplePickerDeptHead');
                Utility.helpers.initializePeoplePicker('peoplePickerITManager');
                Utility.helpers.initializePeoplePicker('peoplePickerFinance');
                //loading SAR data
                $scope.listItemId=Utility.helpers.getUrlParameter('ReqId')
                if ($scope.listItemId != "" && $scope.listItemId != undefined) {
                    loadSARData($scope.listItemId);
                }
            };

            //Load data using querstring
            function loadSARData(listItemId) {
                peopleService.getById(listItemId).then(function (response) {
                    $scope.sarProperties = response.data.d.results[0];
                    //in this field we allow the PeoplePicker column - People and Groups and Allowmultiple=true
                    angular.forEach($scope.sarProperties.DirectManager.results, function (value, key) {
                        Utility.helpers.SetUserFieldValue('peoplePickerDirectManager', value.Title);
                    });
                    //people only -get login name and pass the value instead of title(find exact match)
                    peopleService.getUser($scope.sarProperties.DepartmentHeadId).then(function (response) {
                        Utility.helpers.SetUserFieldValue('peoplePickerDeptHead', response.data.d.LoginName);
                    });
                    //people only
                    peopleService.getUser($scope.sarProperties.ITManagerId).then(function (response) {
                        Utility.helpers.SetUserFieldValue('peoplePickerITManager', response.data.d.LoginName);
                    });
                    //people only
                    peopleService.getUser($scope.sarProperties.FinanceManagerId).then(function (response) {
                        Utility.helpers.SetUserFieldValue('peoplePickerFinance', response.data.d.LoginName);
                    });
                });
            };
            $scope.insertSARRequest = function (type) {
                //get people picker value
                $scope.sarProperties.DirectManager = Utility.helpers.getUserInfo('peoplePickerDirectManager');
                $scope.sarProperties.DepartmentHead = Utility.helpers.getUserInfo('peoplePickerDeptHead');
                $scope.sarProperties.ITManager = Utility.helpers.getUserInfo('peoplePickerITManager');
                $scope.sarProperties.FinanceManager = Utility.helpers.getUserInfo('peoplePickerFinance');
                var list = web.get_lists().getByTitle("SystemRequestList");
                if ($scope.listItemId == "" || $scope.listItemId == undefined) {
                    //insert data to sharepoint
                    var listCreationInformation = new SP.ListItemCreationInformation();
                    var listItem = list.addItem(listCreationInformation);
                } else {
                    var listItem = list.getItemById($scope.listItemId);
                }
                listItem.set_item("FirstName", $scope.sarProperties.FirstName);
                listItem.set_item("LastName", $scope.sarProperties.LastName);
                listItem.set_item("Telephone", $scope.sarProperties.Telephone);
                listItem.set_item("EmployeePosition", $scope.sarProperties.EmployeePosition);
                //people picker field check value
                if ($scope.sarProperties.DirectManager) {
                    listItem.set_item("DirectManager", $scope.sarProperties.DirectManager);
                }
                else {
                    listItem.set_item("DirectManager", null);
                }
                if ($scope.sarProperties.DepartmentHead) {
                    listItem.set_item("DepartmentHead", $scope.sarProperties.DepartmentHead);
                }
                else {
                    listItem.set_item("DepartmentHead", null);
                }
                if ($scope.sarProperties.ITManager) {
                    listItem.set_item("ITManager", $scope.sarProperties.ITManager);
                }
                else {
                    listItem.set_item("ITManager", null);
                }
                if ($scope.sarProperties.FinanceManager) {
                    listItem.set_item("FinanceManager", $scope.sarProperties.FinanceManager);
                }
                else {
                    listItem.set_item("FinanceManager", null);
                }
                listItem.update();
                ctx.load(listItem);
                ctx.executeQueryAsync(function () {
                    alert("saved successfully");

                }, function (sender, args) {
                    console.log("something went wrong");
                    console.log('Err: ' + args.get_message());
                });


            }
        }]);
    </script>
    <style type="text/css">
        .register {
            margin-top: 0%;
            padding: 1%;
        }

        .palel-primary {
            border-color: #bce8f1;
        }

        .panel-primary > .panel-heading {
            /*background:#bce8f1;*/
            background: -webkit-linear-gradient(left, #3931af, #00c6ff);
        }

        .panel-primary > .panel-body {
            background-color: #EDEDED;
        }   
.container {
    width: 100% !important;
}
    </style>
</head>
<body>
    <div ng-app="testApp">
        <div ng-controller="spCustomerController" ng-init="init()">          
            <div class="container register">
                <div class="row">
                    <div class="col-md-12 col-sm-12">
                        <div class="panel panel-primary">
                            <div class="panel-heading">
                                Enter Your Details Here
                            </div>
                            <div class="panel-body">
                                <div class="form-group col-md-6 col-sm-6">
                                    <div class="form-group">
                                        <label for="tNumber">Ticket Number *</label>
                                        <input id="ticketNumber" name="ticketNumber" class="form-control" type="text"  ng-model="sarProperties.TicketNumber"/>                                     
                                    </div>
                                    <div class="form-group">
                                        <label>Request Type</label>
                                        <select name="rType" id="rType" class="form-control" ng-model="sarProperties.RequestType" >
                                            <option selected>New(employee)</option>
                                            <option>test</option>
                                            <option>Other</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label for="lastname">First Name *</label>
                                        <input id="firstName" name="firstName" class="form-control" type="text" ng-model="sarProperties.FirstName" />
                                    </div>
                                    <div class="form-group">
                                        <label for="lastname">Last Name *</label>
                                        <input id="lastname" name="lastname" class="form-control" type="text" ng-model="sarProperties.LastName" />                                      
                                    </div>                                  
                                    <div class="form-group">
                                        <label for="telephone">Telephone *</label>
                                        <input type="text" name="telephone" id="telephone" class="form-control" ng-model="sarProperties.Telephone" />                                    
                                    </div>
                                    <div class="form-group">
                                        <label for="dpet">Department</label>
                                        <select name="department" id="department" class="form-control" ng-model="sarProperties.Department">
                                            <option selected>IS</option>
                                            <option>Finance</option>
                                            <option>Other</option>
                                        </select>                                     
                                    </div>
                                    <div class="form-group">
                                        <label for="phone">Employee Number *</label>
                                        <input type="text" id="eNumber" name="eNumber" class="form-control" ng-model="sarProperties.EmployeeNumber" />                                      
                                    </div>
                                    <div class="form-group">
                                        <label for="emp">Employee Position</label>
                                        <input type="text" name="employeePosition" id="employeePosition" class="form-control" ng-model="sarProperties.EmployeePosition" />                                    
                                    </div>
                                    <div class="form-group">
                                        <label for="asstTag">Asset Tag</label>
                                        <input type="text" name="CSCAssetTag" id="CSCAssetTag" class="form-control" ng-model="sarProperties.CSCAssetTag" />
                                    </div>
                                </div>
                                <div class="form-group col-md-6 col-sm-6">
                                    <div class="form-group">
                                        <label>Finance Manager *</label>
                                        <div title="peoplePickerFinance" id="peoplePickerFinance"></div> 
                                    </div>
                                    <div class="form-group">
                                        <label for="lastname">IT Manager *</label>
                                        <div title="peoplePickerITManager" id="peoplePickerITManager"></div>
                                    </div>
                                    <div class="form-group">
                                        <label>Direct Manager *</label>
                                        <div title="peoplePickerDirectManager" id="peoplePickerDirectManager"></div>
                                    </div>
                                    <div class="form-group">
                                        <label>Department Head</label>
                                        <div title="peoplePickerDeptHead" id="peoplePickerDeptHead"></div>
                                    </div>                              
                                    <div class="form-group">
                                        <label for="disc">Discription</label>
                                        <textarea class="form-control" rows="3"></textarea>
                                    </div>
                                </div>
                                <input id="btnSubmitRequest" value="Submit" ng-click="insertSARRequest('Save')" type="button" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>   
</body>
</html>

No comments:

Post a Comment