How to create views for external lists in SharePoint 2010 using ECMAScript
This blog post explains how to create views for external lists (connected to a WCF Service using BCS) in SharePoint 2010 using ECMAScript. This post will not cover the details about how to create external lists using BCS. For detailed information on this topic please refer the links below.
Connecting to a WCF Service Using Business Connectivity Services in Office 2010
How to: Create External Lists in SharePoint
Creating a View:
Creating a View to an external list is a 2 step process. First step is to create a view and add it to the view collection of the external list. Second step is to update the created view to set the Method XML.
Let us consider that we are creating a view for an external list named Customer. The Customer list is linked to the Customer_ECT external content type. This ECT has the following operations defined.
1. GetCustomerById - Fetches the customer item based on the customer ID
The SP.ViewCreationInformation class will be used to create views for SharePoint Lists.
var listName = "Customer";
var viewName = "Customer_123";
var viewCollection;
function createView() {
var clientContext = new SP.ClientContext.get_current();
if (clientContext != undefined && clientContext != null) {
var web = clientContext.get_web();
var listCollection = web.get_lists();
var list = listCollection.getByTitle(listName);
viewCollection = list.get_views();
var viewInfo = new SP.ViewCreationInformation();
viewInfo.set_title(viewName);
viewInfo.set_rowLimit(2000);
viewInfo.set_personalView(true);
viewCollection.add(viewInfo);
clientContext.load(viewCollection);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onViewCreationSucceeded), Function.createDelegate(this, this.onViewCreationFailed));
}
}
function onViewCreationSucceeded() {
this.clearViewNamesCache();
var clientContext = new SP.ClientContext.get_current();
if (clientContext != undefined && clientContext != null) {
var view = this.viewCollection.getByTitle(viewName);
var query = "<Method Name='GetCustomerById'><Filter Name='customerID' Value='123'/></Method>";
view.set_method(query);
view.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onViewUpdateSucceeded), Function.createDelegate(this, this.onViewUpdateFailed));
}
}
function onViewUpdateSucceeded() {
alert("View Created Successfully");
}
function onViewUpdateFailed(sender, args) {
alert('An error occurred while updating the view');
}
function onViewCreationFailed(sender, args) {
alert('An error occurred while creating the view');
}
Now, call the createView method to create a view for the external list Customer. Thats it!