Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, December 27, 2012

Using jQuery Deferred object with SharePoint Javascript Object Model

One of the common problems with using the SharePoint client object model is the asynchronous nature of the object property calls. For example, if I want to retrieve a current user’s name, I would run code something like this:

context = new SP.ClientContext.get_current();
web = context.get_web();
currentUser = web.get_currentUser();
currentUser.retrieve();
context.load(web);
context.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);


The executeQueryAsync method, after it retrieves the current user information, calls the onQuerySuceeded function that then completes the processing of that request. For example, something like this would be a simple example of that callback



function onSuccessMethod(sender, args) {
var userObject = web.get_currentUser();
alert('User name:' + userObject.get_title());
}


In between the time that the executeQueryAsync is called and the callback to the onSuccessMethod function occurs any other code that was downstream executes. This makes for awkward logic and flow in client object model programs. This is especially true when building larger applications that may want to reuse, let’s say, a function called getUserInformation which returns the current user as an object. This is where a little jQuery magic can come in handy. jQuery supports using what it refers to as Deferreds. Deferreds are based on a CommonJS Promises/A design. At the bottom of this post I will provide a link to documentation on Deferreds and the CommonJS Promise/A design, but for now let’s look at an example of how we can use this.


Let’s say I wanted to build a function like I mentioned above. A function that retrieves the current user’s information and returns that as an object. Since this request is asynchronous, this could normally be very problematic, but with a Deferred object it can be done simply. First, the initial function:

 

function getUserInformation() {
var dfd = $.Deferred(function(){
context = new SP.ClientContext.get_current();
web = context.get_web();
currentUser = web.get_currentUser();
currentUser.retrieve();
context.load(web);
context.executeQueryAsync(
function(){
var userObject = web.get_currentUser();
dfd.resolve(userObject);
},
function(){
dfd.reject(args.get_message());
}
);
});
return dfd.promise();
}

This function creates a Deferred object, then it runs the same code as above to request the current user. The callback functions have been embedded into the executeQueryAsync method so that I can easily reference my existing Deferred object. Notice that the function itself does not return the user object. This is because when the function completes processing the user object has not yet returned. It will be return later asynchronously. Instead, the function returns a promise; a contract that there will be a return value in the future. When the callback does occur then the Deferred object is resolved and any code waiting for the object to return can execute. For illustration purposes here is a simple call to this function that creates a popup message box with the current user’s name (via the title property).

 

getUserInformation().done(function(user){ 
alert('User name:' + user.get_title());
});

The nice feature with this is that if later I want to return that same user’s email address I can just as easily do that reusing the same function:

getUserInformation().done(function(user){ 
alert('Email address:' + user.get_email());
});

To learn more about promises and Deferred objects visit these link

Tuesday, December 18, 2012

Using JsRender with the SharePoint JavaScript Object Model

Are you getting tired of writing a lot of JavaScript to manipulate the DOM while doing client side SharePoint development? This is simple tutorial about using templates with client side SharePoint development to avoid writing a lot of JavaScript to manipulate the DOM.  The template engine used in this tutorial is JsRender, which replaced jQuery templates.  Check out these links for more information on JsRender:

The following example was created in a content editor web part.

Create the HTML:
 
<div id="TasksTable">
<table id="taskTbl" cellpadding="5" cellspacing="5" border="1">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Status</th>
<th>Priority</th>
</tr>
</thead>
<tbody id="taskTblBody">

</tbody>
</table>
</div>


Create the Template Block:
<script id="taskTemplate" type="text/x-jsrender">
<tr>
<td>{{:#data.get_id()}}</td>
<td>{{:#data.get_item('Title')}}</td>
<td>{{:#data.get_item('Status')}}</td>
<td>{{:#data.get_item('Priority')}}</td>
</tr>
</script>
Be sure to include all the files needed:


<script 
type="text/javascript"
src="/sites/Bwarfson/CScripts/jquery-1.7.1.min.js">
</script>
<script
type="text/javascript"
src="/sites/Bwarfson/CScripts/jsrender.js">
</script>


And the JavaScript:
$(document).ready(function() {
if (typeof(_spBodyOnLoadWrapper) != 'undefined')
{_spBodyOnLoadWrapper();} //fix google chrome
ExecuteOrDelayUntilScriptLoaded(function ()
{ retrieveListItems() }, "sp.js");
});

function retrieveListItems() {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext
.get_web()
.get_lists()
.getByTitle('Tasks');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><RowLimit>500</RowLimit></View>");
this.collListItem = oList.getItems(camlQuery);
clientContext.load(
collListItem,
'Include(Id, Title, Status, Priority)'
);
clientContext.executeQueryAsync(
Function.createDelegate(this, function() {
//This is where the magic happens
$( "#taskTblBody" ).append(
$( "#taskTemplate" ).render( collListItem.get_data() )
);
}), Function.createDelegate(this, function(sender, args) {
$('.message').append('<p>Error loading tasks</p>');
$('.message').append('<p>'+args.get_message()+'</p>');
$('.message').append('<p>'+args.get_stackTrace()+'</p>');
}));

}

The final result:

image

Monday, November 5, 2012

Using JavaScript to asynchronously update a xsltlistview webpart

 

In SharePoint 2010 there is an option to “Enable Asynchronous Update”

image

This option exists on each SharePoint 2010 xsltlistview web part.  I had some custom JavaScript that was embedded in a custom action and changed list item values.  I wanted to be able to use this feature to do a no-refresh list view reload.  If you enable the “Show Manual Refresh Button” option you will see the default code that forces a refresh.  It looks something like this:

javascript: __doPostBack('ctl00$m$g_d9ea718d_b0cd_42e5_b4cf_4182334b6861$ctl02','cancel');return false;

Now I just needed a good way to get that same id that is being passed into the __doPostBack function.  Luckily, this value is similar to the GUID of the view for the list.  For example, the view guid of this webpart is {D9EA718D-B0CD-42E5-B4CF-4182334B6861}.  To build the __doPostBack I need to transform the guid to match the format of the ID.  Here is the code I wrote to perform this operation:

var selectedViewId = ctx.view;
var controlId = 'ctl00$m$g_' + selectedViewId.toLowerCase().replace(/-/g, "_").replace(/{|}/g, "") + '$ctl02';
__doPostBack(controlId);

The controlId variable is: the view guid, converted to lowercase, replacing the dashes with underscores, removing the curly braces, attaching ctl00$m$g_ to the front, and $ctl02 to the end.  This seems to work on any xsltlistview web part (whether part of a list view or embedded in a web part page). 

Friday, October 19, 2012

Embedding Javascript in Custom Actions

 

SharePoint 2010 added the ability to tie custom actions to a list or list item:

image

Custom Actions can be added to these menus/ribbons:

image

These custom actions can start workflows, navigate to a form, or navigate to a URL.  This gives some limited customization that can be do to how a list behaves, and what actions can be taken, but with little creativity this functionality can be extended.

The first thing that needs to be understood to extend this functionality is that there a some key tokens that can be used with building URLs.  These tokens are:

  • {ItemId} – ID (GUID) taken from the list view.
  • {ItemUrl} – Web-relative URL of the list item (Url).
  • {SiteUrl} – The fully qualified URL to the site (Url).
  • {ListId} – ID (GUID) of the list (ID).
  • {ListUrlDir} – Server-relative URL of the site plus the list's folder.
  • {Source} – Fully qualified request URL.
  • {SelectedListId} – ID (GUID) of the list that is currently selected from a list view.
  • {SelectedItemId} – ID of the item that is currently selected from the list view.

Source: <http://msdn.microsoft.com/en-us/library/ff458385.aspx>

The other key piece of information needed is that inside the URL can instead be a Javascript function reference like this:

image

Then all that is needed is to create a script library with that function and either reference it on the page (List View), the masterpage, or in the SPWeb property: CustomJavaScriptFileUrl.  For my example I used the following code to create a function that will update any value in the target list item.  The parameters are:

  1. Item ID
  2. List ID
  3. Column Name
  4. New Column Value

The finished Javascript looks like this:

function updateListItem(ItemId, ListId, FieldName, FieldValue) {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getById(ListId);
    var oListItem = oList.getItemById(ItemId);
    oListItem.set_item(FieldName, FieldValue)
    oListItem.update();
    clientContext.load(oListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}


function onQuerySucceeded() {
    window.location.reload(false);
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

With just a little effort now I have a list action that dynamically completes the list item without the overhead of a workflow or making the user open and edit the item:

image

image