Retrieving SP user info using Client Object Model

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.

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('<View><Query><Where><Eq><FieldRef Name=\'ID\' />' +
                                '<Value Type=\'Number\'>' + userId + '</Value></Eq>' +
                                '</Where></Query><RowLimit>1</RowLimit></View>');

    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.


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

SP.SOD.executeOrDelayUntilScriptLoaded(LoadUserInfo, 'SP.js');

Using JsRender to render HTML template

I just happened to use jsrender on my recent project and I have to say that it really helps to simplify my code. jsrender is a javascript templating engine which is used for string based rendering.

For example, let’s say I want to show new employees as below:

So the first thing to do is to get the list of employees as JSON, then I can use JavaScript to manipulate DOM. I could write the following Javascript (which is a bit complicated):

First, the sample data


var employees = [
                                {
                                    Name: "Joe Blogg",
                                    Role: "Software Developer",
                                    Email: "jblogg@email.com"
                                },
                                {
                                    Name: "Jill Blogg",
                                    Role: "Marketing Officer"                                    
                                },
                                {
                                    Name: "Jack Blogg",
                                    Role: "Project Manager",
                                    Email: "jblogg@email.com"
                                },
                                {
                                    Name: "Jon Blogg",
                                    Role: "Software Developer",
                                    Email: "jblogg@email.com"
                                },
                                {
                                    Name: "James Blogg",
                                    Role: "Software Developer"                                    
                                }
            ];

The JavaScript:

var content;
$(employees).each(function (val) {
  content = "<li><ul><li class='innerList'>" + val.Name + "</li>"
              + "<li class='innerList'>" + val.Role + "</li>"
              + "<li class='innerList'>" + val.Email + "</li>"
              + "</ul></li>"
});

$("#dvContainer ul").append(content);

The JavaScript above can get harder to read as the content grows. So let’s look at the jsrender version:

<script id="ViewTemplate" type="text/x-jsrender">    
            
            <li class="outerList">                 
                <ul>
                    <li class="innerList">{{>Name}}</li>
                    <li class="innerList">{{>Role}}</li>
                    <li class="innerList">{{if Email}} {{>Email}} {{else}} ??? {{/if}}</li>
                </ul>                               
            </li>             
    </script>

<script type='text/javascript'>
$("#dvContainer ul").append($("#ViewTemplate").render(employees));
</script>

The jsrender version above uses template which is wrapped in a script tag (there is another way to define the template which can be found on the jsrender site above). The template defines how the data should be displayed. Once we have done the template, we can use the render() function to generate a string that is ready to be inserted to DOM. The {{>}} is jsrender syntax to encode the value.

Please note that you can use jsrender without jquery.

The code for this post can be found in here