Sometimes you would need to fetch the User Id based on either Login name or Email id. You would need User Id if you need to assign a user object to a people picker control or People/Group field.
How do we get the Id based on Email or Login Name in client side development? We can achieve that using JavaScript Object Model or REST API. Let me share the first example using JavaScript Object Model (JSOM).
The above code fetches User Id for a given Login Name or Email Id.
Interestingly, there is no equivalent endpoint available in REST! The Microsoft documentation talk about a endpoint but I could not get it working.
So what is the way to get User Id using REST? You have to use the hidden User Information List. This list contains details about all the users in a SharePoint site. Just like any other List, you can use REST call to fetch data from this list. The REST url looks something like below:
By using the above Url in a ajax call, you can get all the user information including Id.
In case you need to get User Id of a logged in user, you don't have to use any of the above methods, as it is readily available by querying
How do we get the Id based on Email or Login Name in client side development? We can achieve that using JavaScript Object Model or REST API. Let me share the first example using JavaScript Object Model (JSOM).
var context = new SP.ClientContext.get_current();
this.user = context.get_web().ensureUser(loginName or Email);
var o = { d: d, user: this.user };
context.load(this.user);
context.executeQueryAsync(
Function.createDelegate(o, ensureUserSuccess),
Function.createDelegate(o, Fail)
);
The above code fetches User Id for a given Login Name or Email Id.
Interestingly, there is no equivalent endpoint available in REST! The Microsoft documentation talk about a endpoint but I could not get it working.
So what is the way to get User Id using REST? You have to use the hidden User Information List. This list contains details about all the users in a SharePoint site. Just like any other List, you can use REST call to fetch data from this list. The REST url looks something like below:
_spPageContextInfo.webAbsoluteUrl + "/_api/web/SiteUserInfoList/items?$filter=EMail eq '" + EmailId + "'";
By using the above Url in a ajax call, you can get all the user information including Id.
In case you need to get User Id of a logged in user, you don't have to use any of the above methods, as it is readily available by querying
_spPageContextInfo.userId
property.
Comments
Post a Comment