Skip to main content

Get Login user name and details for SharePoint 2013 Online (Office 365)List New Form using REST API

Display login user name and details on SharePoint online(Office 365) List New Form.



Step 1: Create people picker column(In my case, created 'From'column).




Step 2: Open your List new form using SP Designer add tdFrom id for description filed.



Step 3: Add the below code in script tag and add SharePoint Services and J query reference files(Download latest files).

<script type="text/javascript" src="../../Style Library/Scripts/jquery-3.0.0.min.js"></script>
<script type="text/javascript" src="../../Style Library/Scripts/jquery.validate.min.js"></script>
<script type="text/javascript" src="../../Style Library/Scripts/jquery.SPServices-2014.02.min.js"></script>
<script type="text/javascript" >
$(document).ready(function() 
{
var fieldName ='From';
var userAccountName= $().SPServices.SPGetCurrentUser();
LoadPeoplePickerDetails();

 }); 
 //Function to set people picker values
function LoadPeoplePickerDetails()
{
var url=_spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties"
getReqData(url,function(data){ 
try 
{
            //Get properties from user profile Json response  
            var userDisplayName = data.d.DisplayName;
            var AccountName = data.d.AccountName;
     $("#tdFrom [id$='upLevelDiv']").html(AccountName);
     $("#tdFrom [id$='checkNames']").click();
}
catch(err){

}         
},
function(data){
//alert("Error occured in getting current User info");
});
}
function getReqData(reqUrl,success, failure) {
$.ajax({
url: reqUrl, 
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
}

</script>
Step 4: Save the form. Happy Coding!.

Get Login User Details on SharePoint Online (Office 365) Page load using REST API.




Step 1 : Download Plus/Minus images from google and upload these images to SiteAssets/Images document library.




Step 3 : Add below code in new custom list form.

<tr>
<td>
<span id="ProfileDetails">
<img class="imgPlusMinus" alt ="" src="../../SiteAssets/Images/plus.png"/>
<b style="padding-left:5px">Requestor Details</b>
</span>
</td>
<td>
</td>
</tr>
<tr>
<td colspan="2">
<div id="divRequestorDetails"></div>
<br/>
</td>
</tr>



Step 4Add the below code in script tag and add SharePoint Services and J query reference files(Download latest files).

<script type="text/javascript" src="../../SiteAssets/Scripts/jquery-3.0.0.min.js"></script>
<script type="text/javascript" src="../../SiteAssets/Scripts/jquery.SPServices-2014.02.min.js"></script>
<Script type="text/javascript" src="../../SiteAssets/Scripts/jquery.validate.min.js"></Script>

var plusMinusImgUrl = '../../SiteAssets/Images/';

<Script type="text/javascript">


$(document).ready(function(){


var invokeAfterEntityEditorCallback =  function(func) {
   var old__EntityEditorCallback = EntityEditorCallback;
   if (typeof EntityEditorCallback != 'function') {
       EntityEditorCallback = func;
   } else {
       EntityEditorCallback = function(result, ctx) {
           old__EntityEditorCallback(result, ctx);
           if(ctx.indexOf('ff31')>-1)
           {
        func(result, ctx);
        }
       }
   }
};
function onPeoplePickerFieldSet(result, ctx){
getO365RequestorUserProfile(); 
}
invokeAfterEntityEditorCallback(onPeoplePickerFieldSet);


 $("#ProfileDetails").click(function () {
        getO365RequestorUserProfile();
        var imgPlusMinus = $(this).find('img');
        var src = (imgPlusMinus.attr('src') == plusMinusImgUrl + 'Minus.png') ? plusMinusImgUrl + 'Plus.png' : plusMinusImgUrl + 'Minus.png';
        $(imgPlusMinus).attr('src', src);
        if (flag == 1) {
            $('#tblRequestorDetails').show();
            flag = 0;
        } else {
            $('#tblRequestorDetails').hide();
            flag = 1;
        }
    });

}); 
//Get Office 365 User Profile
function getO365RequestorUserProfile() {
   var loginName = encodeURIComponent($("div[id*='divEntityData']").attr('key'));
var tblreqdisp=$('#divRequestorDetails #tblRequestorDetails').css('display');
   var userData = [];
   var table = "<table id='tblRequestorDetails' class='tblRequestorDetails' width='900'";
if(tblreqdisp!='table')
{
    table+=" style='display:none' ";
   }
   table+="cellSpacing='1' cellPadding='2' bgColor='#dddddd' border='0' valign='top'>";
   var siteUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='" + loginName + "'";
   $.ajax({
       url: siteUrl,
       type: "GET",
       async: false,
       headers: { "Accept": "application/json; odata=verbose" },
       success: function (data) {
           var profileData = data.d;
           if (profileData != null) {
               var accName = profileData.AccountName.split('|')[2];
               var dispName = profileData.DisplayName;
               var dispEmail = profileData.Email;
               var title = profileData.Title;
               userData.push({ Name: 'AccountName', Value: accName });
               var allProperties = profileData.UserProfileProperties.results;
               if (allProperties.length > 0) {
                   for (var i = 0; i < allProperties.length ; i++) {
                       var department = allProperties[i].Key == 'Department' ? userData.push({ Name: 'Department', Value: allProperties[i].Value }) : "";
                       var manager = allProperties[i].Key == 'Manager' ? userData.push({ Name: 'Manager', Value: allProperties[i].Value.split('|')[2] }) : "";
                       var userName = allProperties[i].Key == 'UserName' ? userData.push({ Name: 'User Name', Value: allProperties[i].Value }) : "";
                       var workEmail = allProperties[i].Key == 'WorkEmail' ? userData.push({ Name: 'Work Email', Value: allProperties[i].Value }) : "";
                       var location = allProperties[i].Key == 'SPS-Location' ? userData.push({ Name: 'Work Location', Value: allProperties[i].Value }) : "";
                       var WorkPhone = allProperties[i].Key == 'WorkPhone' ? userData.push({ Name: 'WorkPhone', Value: allProperties[i].Value }) : "";
                   }
                   for (var j = 0; j < userData.length; j++) {
                       table += "<tr><td width='190px' valign='top' class='ms-formlabel' bgcolor='#eeeeee' rowSpan='1' colSpan='1'>" + userData[j].Name + "</td>"
                        + "<td width='400px' valign='top' class='ms-formlabel' style='background-color: white;' rowspan='1' colSpan='1'>" + userData[j].Value + "</td></tr>";
                   }
                   table += "</table>";
                   $('#divRequestorDetails').html(table);
               }
           }
       },
       error: function (data) {
           //console.log(error);  
       }
   });
}
</script>

Step 5 : Save the form. Happy Coding. !







Comments

Popular posts from this blog

Tab Control in Asp.Net

Scenerio: I need your help in designing tab control in   asp.net .My requirement is I need a tab control in   asp.net (C#) like  for example goto my computer ,right click c drive and select properties.we get tabs like general,security etc....... like that i need to design one tab control(no need of any rightclick) in my web page and the database table columns should come as tabs and inseide the tab data of that particular column should come.   Example:Employee master tab1:Employee name.........his name in the tab tab2:Age.............his age tab3:Address........his address   Solution:   You can do this using a simple div <style type="text/css"> .tabs         {             position: relative;             height: 20px;             margin: 0;   ...

AI and Microsoft: Revolutionizing Efficiency in Nonprofit Organizations

  How AI and Microsoft Enhance Efficiency in Nonprofit Organizations In today’s fast-paced world, nonprofit organizations face unique challenges—limited resources, increasing demands, and the constant need to do more with less. But what if technology could be the game-changer they need? In my latest research paper,  "How AI and Microsoft Enhance Efficiency in Nonprofit Organizations" , I explore how cutting-edge technologies like Artificial Intelligence (AI) and Microsoft’s innovative tools are revolutionizing the way nonprofits operate. From streamlining administrative tasks to enhancing donor engagement and optimizing resource allocation, AI and Microsoft’s solutions are empowering nonprofits to focus on what truly matters—their mission. This paper dives deep into real-world examples, practical applications, and the transformative potential of these technologies. Whether you’re a nonprofit professional, a tech enthusiast, or simply curious about the intersection of technolo...

Social tagging overview in Sharepoint 2010

A tag is a word or phrase that identifies an individual piece of information according to a set of attributes or criteria. Tags make it easy to find and share information about a specific subject or task. Social tagging helps users categorize information in ways that are meaningful to them. Social tagging can improve the quality of search results by filtering against specific tags, and it can also connect individuals who want to share information with other users who have like interests. This article describes the social tagging features in Microsoft SharePoint Server 2010. This article does not describe how to configure social tagging features. It also does not discuss how to implement social tagging features as part of an overall social media strategy for an enterprise. About using social tagging features Social tagging features help users to share information and to retrieve relevant, high-quality content more efficiently. Such sharing encourages collaboration and b...