0

I have built a custom people picker field with submit button in SharePoint webpart. The people picker field is rendering people from SharePoint.

Now, I want when I select a particular user in people picker field and click on submit button it should send the entry to my SharePoint list. I have built this field and also able to render people in suggestion but unable to post data into SharePoint list, here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom People Picker</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.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>  
</head>
<body>
<div class="people-picker-container">
  <div class="input-container">
    <label for="assign">Assign:</label>
  </div>
</div>
<div id="assignField"></div>

<button id="submitBtn">Submit</button>

<script>
$(document).ready(function() {
    initializePeoplePicker("assignField");
    
    // Attach click event to the submit button
    $('#submitBtn').on('click', function() {
        ensureUserAndSaveToList('CreateBenefits');
    });
});

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';
    
    // Initialize the People Picker control
    this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
    
    // Populate suggestions from SharePoint list column
    populatePeoplePickerSuggestions(peoplePickerElementId);
}

function populatePeoplePickerSuggestions(peoplePickerElementId) {
    // Fetch data from SharePoint list column "Assign" using REST API
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('CreateBenefits')/items?$select=Assign",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function(data) {
            console.log("Data retrieved successfully:", data);
            var suggestions = [];
            // Extract user names from the retrieved data
            data.d.results.forEach(function(item) {
                suggestions.push(item.Assign);
            });
            // Populate the People Picker control with suggestions
            var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerElementId];
            peoplePicker.AddUserKeys(suggestions.join(";"));
        },
        error: function(error) {
            console.log("Error fetching data from SharePoint list: " + JSON.stringify(error));
        }
    });
}

function ensureUserAndSaveToList(listName) {
    var peoplePickerTopDivId = $('#_UserName').children().children().attr('id');
    var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerTopDivId];
    var users = peoplePicker.GetAllUserInfo();
    var UserId = 0;

    if (users.length > 0) {
        var arryuser = users[0];
        var payload = { 'logonName': arryuser.Key };
        
        // Ensure the user exists
        $.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) {
                console.log("Error ensuring user: " + JSON.stringify(error));
            }
        });
    }

    // Save data to SharePoint list
    if (UserId !== 0) {
        $.ajax({
           url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('" + listName + "')/items",
            type: "POST",
            async: false,
            data: JSON.stringify({
                __metadata: {
                    type: "SP.Data.PeopleListItem"
                },
                UserNameId: UserId
            }),
            headers: {
                "Accept": "application/json;odata=verbose",
                "Content-Type": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "POST",
            },
            success: function (data) {
                console.log("User Name is saved successfully");
                alert("User Name is saved successfully");
            },
            error: function (error) {
                console.log("Error saving user name: " + JSON.stringify(error));
                alert("Error saving user name: " + JSON.stringify(error));
            }
        });
    } else {
        console.log("No user selected");
        alert("No user selected");
    }
}
</script>
</body>
</html>

If Anyone know how to post data to SharePoint list please let me know.

6
  • Do you get any error while using above code? If yes, can you share the error message? Is "UserName" field in list is single selection people field or multiple selection? Commented Apr 4, 2024 at 10:16
  • getting alert while submitting entry "Error saving user name" , UserName field is single selection people field Commented Apr 4, 2024 at 10:20
  • Do you get any error message from API call while using this: JSON.stringify(error)? I am guessing this part in your code is wrong: __metadata: { type: "SP.Data.PeopleListItem" }. Hence I want to confirm error message you get from API call. Commented Apr 4, 2024 at 10:27
  • Confirm if you are using correct type by following solution given at: sharepoint.stackexchange.com/questions/267243/…. Let me know if it works for you. Commented Apr 4, 2024 at 10:30
  • no, provided link solution is not helping plus not getting any error in API Commented Apr 4, 2024 at 10:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.