Display current logged in User in a SharePoint Page or Form - Fabian Neve

About SharePoint, Javascript, PowerShell, and other technical stuff

Monday, October 9, 2017

Display current logged in User in a SharePoint Page or Form

If you like to show the current logged-in User in a Page or a Form (eg. NewForm.aspx), you can use following JavaScript code. Insert it via script editor/code snippet and don't forget to reference a Javascript file (<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>).

<script type="text/javascript">
var loginName = "";
var userid = _spPageContextInfo.userId;
GetCurrentUser();
function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : onSuccess,
error : onError
});
}
function onSuccess(data, request) {
var loginName = data.d.Title;
// alert("Hello " + loginName);
// to set the "hello username" into the page
document.getElementById("welcome").innerHTML = loginName;
}
function onError(error) {
alert(error);
}
</script>
With that code, you can insert the Username into a div with the ID "welcome" (choose any ID you want, just change it in the script).

I used that code for a NewForm.aspx, the goal was to display the current User on top of the form. So I added folllowing HTML after the javascript code:

<html>
<table width="100%" class="ms-formtable" style="margin-top: 8px;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="103" class="ms-formlabel" nowrap="true" valign="top"><h3 class="ms-standardheader"><nobr>User</nobr></h3></td>
<td width="350" class="ms-formbody" valign="top" id="welcome"></td>
</tr>
</tbody>
</table>
</html>
view raw table.html hosted with ❤ by GitHub

The result will be something like this - just edit the html accordingly:




No comments:

Post a Comment