Pre-populate user details on NewForm.aspx with a Script Editor Web Part
- SharePoint
- Posted by: Hayden Sinclair
- font size decrease font size increase font size
Your method varies depending on whether your form is an out of the box (i.e. NewForm.aspx) or customised SharePoint form (i.e. a new form page created in SharePoint Designer).
This post describes how to pre-populate user details on an out of the box NewForm.aspx using a Script Editor Web Part. If you have customised your page in SharePoint Designer, see Pre-populate Current User on a customised MyNewForm.aspx page
InfoPath
If you are an InfoPath Developer then setting the Current User Details in an InfoPath Form is a straightforward process. Well as long as your SharePoint Installation is on-premise.If you are using SharePoint Online, there is workaround, for finding user details in an Office 365 InfoPath Form. Though this method is not nearly as powerful.
Set username on NewForm.aspx with Script Editor Web Part
To pre-populate user details on an out of the box SharePoint NewForm.aspx page follow these instructions.Download the latest jquery SP Service (i.e. jquery.SPServices-0.5.3.min.js) then upload your jquery file to your Site Assets library.
Copy the script below and paste it into Notepad
<script src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="/sites/MySharePointSite/SiteAssets/jquery.SPServices-0.5.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var loginName= $().SPServices.SPGetCurrentUser();
SetUserFieldValue("Requested By",loginName);
function SetUserFieldValue(fieldName, userName) {
var _PeoplePicker = $("div[title='" + fieldName + "']");
var _PeoplePickerTopId = _PeoplePicker.attr('id');
var _PeoplePickerEditer = $("input[title='" + fieldName + "']");
_PeoplePickerEditer.val(userName);
var _PeoplePickerOject = SPClientPeoplePicker.SPClientPeoplePickerDict[_PeoplePickerTopId];
_PeoplePickerOject.AddUnresolvedUserFromEditor(true);
}
});
</script>
Update the jquery link on line 32 to point to jquery in your SharePoint Site Assets library.
<script src="/sites/MySharePointSite/SiteAssets/jquery.SPServices-0.5.3.min.js" type="text/javascript"></script>
Update
SetUserFieldValue("Requested By",loginName); on line 37 to the name of
the people picker field in your form. Type the field label exactly
here (e.g. Manager Name, or Approved By etc).
SetUserFieldValue("Requested By",loginName);
Copy your script again.
Go to the NewForm.aspx page (you can get there by clicking the New button).
Click Cog > Edit page
Click Add a Web Part
Choose Media and Content > Script Editor
Click Add
Click Edit Snippet, paste in your code, and click Insert
Select the Page Ribbon, then click Stop Editing
Finished. Now when a user creates a New Form, their username will populate in the Requested By people picker field.