SharePoint Online: Set Current User as Default Value in Person or Group Field

Requirement: Fill the Current user in person or group field (People Picker column) in SharePoint Online list New form.

How to Set the Person or Group Field Default Value as Current User in SharePoint Online?
I have a list to track travel requests and want to fill some people picker columns to currently logged in user. To fill the currently logged in user to person or group field's value, just edit the newform.aspx and add a script editor web part in it and then place the below script in it. This works only in "classic experience".
<script src="https://crescent.sharepoint.com/sites/Intranet/SiteAssets/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
    SP.SOD.executeOrDelayUntilScriptLoaded(loadCurrentUser, 'clientpeoplepicker.js');
});

function loadCurrentUser() {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
        var currentUserRequest = $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + '/_api/web/currentuser',
            method: 'GET',
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose"
            }
        });

        currentUserRequest.done(function (result) {
            var userObj = { 'Key': result.d.Email };
            var TravelerPeoplePickerCtrlId = $('nobr:contains("Name of the Traveler")').closest('tr').find('div.sp-peoplepicker-topLevel').attr('id');
            var TravelerPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[TravelerPeoplePickerCtrlId];
            TravelerPeoplePicker.AddUnresolvedUser(userObj, true);
        });
    });
}
</script>
Make sure the "Name of the Traveler" is the Title of the People picker field.
sharepoint online fill current user in person or group field in list new form

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.