Friday, October 19, 2012

Embedding Javascript in Custom Actions


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


Custom Actions can be added to these menus/ribbons:


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: <>

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


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)
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

function onQuerySucceeded() {

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:



No comments:

Post a Comment