Monday, June 13, 2011

Check-in & Check-out using ECMA script in SharePoint 2010

Recently, I had to enable editing just the content (not web part zones) of a publishing page by end users without the ribbon. I decided to make use of the ECMA script model to empower end users to update just the content of the page.

Provide buttons for different operations of a publishing page (edit, save and cancel) and handle the events in javascript coding and some jQuery.

I came across Sohel's blog with a pretty good description of how to make use of the ECMA script. It is basically, all the updates need to be set in its corresponding javascript objects and then "executeQueryAsync" must be called on the ClientContext object to save everything on to the server.

One porblem I faced was updating a particular field content in the current list item being edited. After doing some research on MSDN, I came across this function SP.File.listItemAllFields on MSDN (http://msdn.microsoft.com/en-us/library/ee557727.aspx) and started down that path.

I was able to check-out the current PublishingPage, update the corresponding list item and publish the page using current user's permissions.

function checkOut(){
        var ctx = SP.ClientContext.get_current();
        var page = ctx.get_web().getFileByServerRelativeUrl(window.location.pathname);
        page.checkOut();
        ctx.load(page);
        ctx.executeQueryAsync(Function.createDelegate(this, checkOut_Success),
                                            Function.createDelegate(this, checkOut_Fail));
}
function checkOut_Success(sender, args){
        //Do all sort of jquery to insert your own RTE control to edit the page contents
}
function checkOut_Fail(sender, args){
       //Do some error checking
}

function checkIn(){
         var ctx = SP.ClientContext.get_current();
        var web = ctx.get_web();
        var page = web.getFileByServerRelativeUrl(window.location.pathname);

        if (contentEditorNicInstance != null) {
            var listItem = page.get_listItemAllFields();
            listItem.set_item("PublishingPageContent", "{Updated content from the UI}");
            listItem.update();
        }
        page.checkIn();
        page.publish();
        ctx.executeQueryAsync(Function.createDelegate(this, checkIn_Success),
                                            Function.createDelegate(this, checkIn_Fail));
}
function checkIn_Success(sender, args){
       //This is to refresh the page after successful publishing with the new updated content.
      //If the page is not refreshed, the ECMA script will not support further check-in's and comes back with an error as "version conflict"
       window.location = window.location;
}
function checkIn_fail(sender, args){
      //Handle the error message
}

I think I am helping myself to remember this in future and also few others with their coding.

Senthil


No comments:

Post a Comment