In this previous post, I used jQuery/SOAP/SPServices to access a SharePoint BCS list (an external list). I wanted to do the same thing using the Client Object Model (Some call it Clien OM? Or maybe CSOM?). Below is the code to access contact data in a BCS connection to Microsoft CRM 2011, and use it for autocomplete values. Things to note:
- You need to have a method tag in your CAML statement. This tells the list which “Operation” (as it is listed in SharePoint Designer) to use
- You need to use the “include method” with the executeQueryAsync method
- You need to include the ViewFields tags in the CAML statement, and I think they should match the include statement above
$('#ContactsSearchTextbox').autocomplete({
source: function( request, response ) {
var CAMLQuery= "<View><Method Name='ContactReadList' /><Query><Where><Contains><FieldRef Name='FullName' /><Value Type='Text'>"+request.term+"</Value></Contains></Where></Query><ViewFields><FieldRef Name='FullName' /><FieldRef Name='ContactId' /><FieldRef Name='ParentCustomerIdName' /></ViewFields></View>";
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('Contacts');
var query = new SP.CamlQuery;
query.set_viewXml(CAMLQuery);
allItems = list.getItems(query);
context.load(allItems, 'Include(FullName,ContactId,ParentCustomerIdName)');
context.executeQueryAsync(function (){
var arrayOfResults = new Array();
var listItemEnumerator = allItems.getEnumerator();
while(listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
arrayOfResults.push(oListItem);
}
response($.map(arrayOfResults ,function( item ) {
return {
label: item.get_item('FullName') + ' (' + item.get_item('ParentCustomerIdName') + ')',
value: item.get_item('ContactId'),
id: item.get_item('FullName')
}
}));
},function(sender, args){
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
});
},
minLength: 5,
});