Search This Blog

Tuesday, October 4, 2016

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. !







No comments:

Post a Comment