Monday, January 7, 2019

People Picker- SharePoint 2013 using JavaScript

People picker Save to custom List
--------------------------------------------

step 1: create one TestList with AssigningTo - persona and Group column type
step 2: create one testPage add scripteditor webpart and insert below code.

<html>
    <head>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <script type="text/javascript" src="_layouts/15/clienttemplates.js"></script>
            <script type="text/javascript" src="_layouts/15/clientforms.js"></script>
            <script type="text/javascript" src="_layouts/15/clientpeoplepicker.js"></script>
            <script type="text/javascript" src="_layouts/15/autofill.js"></script>
            <script>
                var UserId;
                var listname = "TestList";

                $(document).ready(function () {
                    initializePeoplePicker("_UserName");
                });

                function initializePeoplePicker(peoplePickerElementId) {
                    var schema = {};
                    schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
                    schema['SearchPrincipalSource'] = 15;
                    schema['ResolvePrincipalSource'] = 15;
                    schema['AllowMultipleValues'] = false;
                    schema['MaximumEntitySuggestions'] = 50;
                    schema['Width'] = '280px';

                    this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
                }

                function saveUser() {
                    ensureUser();
                    $.ajax({
                        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('"+ listname + "')/items",
                        type: "POST",
                        async: false,
                        data: JSON.stringify({
                            __metadata: {
                                type: "SP.Data.TestListListItem"
                            },
                            AssigningToId: UserId
                        }),
                        headers: {
                            "Accept""application/json;odata=verbose",
                            "Content-Type""application/json;odata=verbose",
                            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                            "X-HTTP-Method""POST",
                        },
                        success: function (data) {
                            alert("User Name is saved successfully");
                        },
                        error: function (error) {
                            alert(JSON.stringify(error));
                        }
                    });
                    //alert("Yes");
                }

                function ensureUser() {
                    var peoplePickerTopDivId = $('#_UserName').children().children().attr('id');
                    var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerTopDivId];
                    var users = peoplePicker.GetAllUserInfo();
                    var arryuser = users[0];
                    if (arryuser) {
                        var payload = { 'logonName': arryuser.Key };
                        $.ajax({
                            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/ensureuser",
                            type: "POST",
                            async: false,
                            contentType: "application/json;odata=verbose",
                            data: JSON.stringify(payload),
                            headers: {
                                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                                "accept""application/json;odata=verbose"
                            },
                            success: function (data, status, xhr) {
                                UserId = data.d.Id;
                            },
                            error: function (xhr, status, error) {
                            }
                        });
                    }
                    else {
                        UserId = 0;
                    }

                }
            </script>
    </head>
    <body>
        <div>
            <label>User Name:</label>
            <div id="_UserName" class="peoplepicker"></div>
        </div>
        <div>
            <button type="button" id="btnSubmit" onclick="saveUser()" style="margin-top10px;">Submit</button>
        </div>
    </body>

</html>

refer :https://www.c-sharpcorner.com/article/custom-people-picker-in-sharepoint-online/


---------------------------------------Another one-----------------------------------------


Step 2 : Paste below code.

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="http://onlinesite/_layouts/15/clientpeoplepicker.js"></script>
<script src="http://onlinesite/_layouts/15/clienttemplates.js"></script>
<script src="http://onlinesite/_layouts/15/clientforms.js"></script>
<script src="http://onlinesite/_layouts/15/sp.core.js"></script>
<script src="http://onlinesite/_layouts/15/sp.runtime.js"></script>
<script src="http://onlinesite/_layouts/15/autofill.js"></script>
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(getUserInformation, "sp.js");
      function getUserInformation() {

          var context = new SP.ClientContext.get_current();
          var web = context.get_web();
          var currentUser = web.get_currentUser();

          initializePeoplePicker('peoplePickerDiv');

      }
      // Render and initialize the client-side People Picker.
      function initializePeoplePicker(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.
          this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
      }

      function getUserInfo() {

          // Get the people picker object from the page.
          var peoplePicker =this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;
          var displytext = "";
          // Get information about all users.
          var users = peoplePicker.GetAllUserInfo();
          var userInfo = '';
          for (var i = 0; i < users.length; i++) {
              var user = users[i];
              for (var userProperty in user) {
                  userInfo += userProperty + ':  ' + user[userProperty] + '<br>';
                  displytext= user["DisplayText"];
              }
          }
          $('#resolvedUsers').html(userInfo);

          // Get user keys.
          var keys = peoplePicker.GetAllUserKeys();
          $('#userKeys').html(keys);
          document.getElementById("txtUser").value = keys;
          document.getElementById("txtUserName").value = displytext;
      }

</script>

<div style="background-color:red" id="peoplePickerDiv">

</div>
<div>
    <br />
    <input type="text" id="txtUser" />
    <input type="text" id="txtUserName" />
    <input type="button" value="Get User Info" onclick="getUserInfo()"></input>
    <br />
    <h1>User info:</h1>
    <p id="resolvedUsers"></p>
    <h1>User keys:</h1>
    <p id="userKeys"></p>
    <h1>User ID:</h1>
    <p id="userId"></p>
</div>

No comments:

Post a Comment

Creating Provider hosted app (sharepoint online) with local hosted IIS

The Pre-requires are as follows. 1. Office 365 Subscription 2. Visual Studio 2015 (Professional/Community/Enterprise Edition) With t...