Monthly Archives: November 2014

Client Side Object Model (CSOM) only works in Page Edit Mode

Following my previous post with accessing SharePoint List items using REST API, I’m starting to use Client Side Object Model in the Script Editor Webpart. Then, I found another issue where my CSOM script is only works when the Page in Edit mode. Why would that be ? Why I found two strange things in a week ?

After analyzing and placing breakpoints to the script using developer tools F12, I’ve found that the Out of the Box SharePoint javascript sp.js is not yet loaded when my script executed. Then, I realize my CSOM script really need something to ensure sp.js loaded prior executing my CSOM script => SP.SOD.executeFunc.

Below is my updated code:

<script type="text/javascript">
var ctx;
var listTitle = "My list";
var list;
var items;

// Ensure 'sp.js' is loaded before your code runs.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointListReady);

// Create an instance of the current context.
function sharePointListReady() {
 ctx = SP.ClientContext.get_current();
 list = ctx.get_web().get_lists().getByTitle(listTitle);
 var query = new SP.CamlQuery();
 query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='ID'/><Value Type='Counter'>1</Value></Eq></Where></Query></View>";
 items = list.getItems(query);
 ctx.load(items);
 ctx.executeQueryAsync(onRequestSucceeded, onRequestFailed);
}

function onRequestSucceeded() {
 var itemValues = items.getItemAtIndex(0).get_fieldValues();
 alert(itemValues.Title);
}

function onRequestFailed(sender, args) {
 alert('Error: ' + args.get_message());
}
</script>

It works ! great… But the code above returns all items =( it seems like the Caml Query not working. I’ve stuck for quite sometime googling and I found msdn article that use query.set_viewXml(query) to set the Caml Query instead of query.ViewXml. This time is really working.

Below is my final code:

<script type="text/javascript">
var ctx;
var listTitle = "My list";
var list;
var items;

// Ensure 'sp.js' is loaded before your code runs.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointListReady);

// Create an instance of the current context.
function sharePointListReady() {
 ctx = SP.ClientContext.get_current();
 list = ctx.get_web().get_lists().getByTitle(listTitle);
 var query = new SP.CamlQuery();
 query.set_viewXml("<View><Query><Where><Eq><FieldRef Name='ID'/><Value Type='Counter'>1</Value></Eq></Where></Query></View>");
 items = list.getItems(query);
 ctx.load(items);
 ctx.executeQueryAsync(onRequestSucceeded, onRequestFailed);
}

function onRequestSucceeded() {
 var itemValues = items.getItemAtIndex(0).get_fieldValues();
 alert(itemValues.Title);
}

function onRequestFailed(sender, args) {
 alert('Error: ' + args.get_message());
}
</script>

References

Advertisements

Retrieve Publishing Image column from SharePoint REST API

Recently, I utilized SharePoint REST API to retrieve list item and one of the column is Publishing Image. I’m half surprise and half confuse why the Publishing Image column is not returned by the REST API. Trying to create a new custom list with Out of the Box Publishing Image site column (Page Image) and I still cannot find the publishing image column from REST API call result.

http://siteurl/_api/web/lists/getbytitle(“listTitle&#8221;)/items?$filter=Active eq 1&$select=Title,PublishingPageImage

Quickly google it and found this post and I’m feeling devastated. Why would you want to make a second call just for the one column.

Below is the same code from the post and Thanks to Vadim Gremyachev

function getJson(endpointUri, success, error)
{
    $.ajax({
       url: endpointUri,
       type: "GET",
       processData: false,
       contentType: "application/json;odata=verbose",
       headers: {
          "Accept": "application/json;odata=verbose"
       },
       success: success,
       error: error
    });
}

function getPublishingPage(webUrl,listName,listItemId,publishingProperties, success, failure)
{
    var itemUri =  webUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + listItemId + ")";
    getJson(itemUri,
       function(data){
           var pageItem = data.d;

           var selectProperties = [];
           for(var idx in publishingProperties){
               if(!pageItem.hasOwnProperty(publishingProperties[idx])){
                   selectProperties.push(publishingProperties[idx]);
               }
           }
           if(selectProperties.length > 0) {
              //construct an additional query
              var query = '/FieldValuesAsHtml?$select=' + selectProperties.join(',');
              var endpointUri = pageItem['__metadata'].uri + query;
              getJson(endpointUri,
                 function(data){
                    for(var property in data.d){
                       if(property == "__metadata") continue;
                       pageItem[property] = data.d[property];
                    }
                    success(pageItem);
                 },
                 failure);
           }
           else {
              success(pageItem);
           }
        },
       failure);
}

getPublishingPage(_spPageContextInfo.webAbsoluteUrl,'Pages',3,['PublishingRollupImage','PublishingPageImage'],printPageDetails,logError);

function printPageDetails(pageItem)
{
    console.log('Page Content: ' + pageItem.PublishingPageContent);
    console.log('Page Title: ' + pageItem.Title);
    console.log('Page Rollup Image ' + pageItem.PublishingRollupImage);
}

function logError(error){
    console.log(JSON.stringify(error));
}

References

http://stackoverflow.com/questions/25852997/retrieve-publishing-image-field-with-sharepoint-2013-rest-api-csom

%d bloggers like this: