Saturday 19 January 2013

Modifying the list view using ECMASCRIPT


​Lately I came across a requirement where I was supposed to modify the list view using javascript client object model. The requirement was that I had to fetch a view of a list from sharepoint which had certain fields in it which were not there in the existing view of the list. Now the problem was that how much hard I tried to update the view and set the view query for the view fields of my interest it was not getting updated. When I tried to debug my javascript in the browser my query was actually updating the view fields but the view was not getting updated.

Below is what I was trying



var query = "<View><ViewFields><FieldRef Name='Field1'/><FieldRef Name='Field2'/><FieldRef Name='Field3'/></ViewFields></View>";

var views = list.get_views();

var view = views.getByTitle("All Items");

view.set_viewQuery(query);

view.update();

So after some playing around with javascript, I came up to an approach that was able to update the view as per my desired view fields.

var views = list.get_views();

var view = views.getByTitle("All Items");

view.get_viewFields().removeAll();
view.get_viewFields().add("Field1");

view.get_viewFields().add("Field2");

view.get_viewFields().add("Field3");

view.update();



Doing this will add the desired fields to the view and fetch them. There is one flaw with this approach however. It will modify the existing view on the list. In case you donot want that to happen then you can try creating a custom view based on the existing view. I have not tried that its a thought.

It was something that I struggled for a few hours so making a note of it through this post. :)



-Geetanjali

No comments:

Post a Comment