Friday, March 21, 2014

Retrieving SP user info using Client Object Model

copyright: akurniaga.wordpress.com


Recently I built a visual web part to show current user’s information (Picture, Name, etc). Instead of using SharePoint server object model, this time I choose to use client OM. First I need to get the id of the logged-in user, which can be retrieved from _spPageContextInfo.userId (Ted Pattison has posted an excellent article explaining this variable). Next step is to get the client context.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var context = new SP.ClientContext.get_current();
    var web = context.get_web();
 
    var userInfoList = web.get_siteUserInfoList();
 
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('' +
                                '' + userId + '
' +
                                '
1');
 
    this.userListItem = userInfoList.getItems(camlQuery);
 
    context.load(this.userListItem);
 
    context.executeQueryAsync(
            Function.createDelegate(this, onSucceeded),
            Function.createDelegate(this, onFailed));
The onSucceeded function is called when the query runs successfully, otherwise the onFailed function will be executed.
1
2
3
4
5
6
7
8
9
10
11
12
function onSuceeded(sender, eventArgs)
{
        var item = this.userListItem.itemAt(0);
        var name = item.get_item('Name');
        var userName = "Name";
 
        if (name) {
            userName = name;
        }
 
        alert(userName);
}
One last thing to remember is to run the code after SP.js is loaded
1
SP.SOD.executeOrDelayUntilScriptLoaded(LoadUserInfo, 'SP.js');

No comments: