I am trying to write javascript CSOM code to programmatically create a StaleContent view on every document library in each of 50 site collections, rather than having to do it manually.
The filter condition I want to apply to the view is "Modified"; "is less than or equal to"; "[Today]-1005". (translation: show me only documents with a modified date older than 2 years and 9 months). For testing purposes, instead of "[Today]-1005" I am using just "[Today]".
My code is successfully creating the StaleContent view and including the filter condition I want, but the view does not actually work until I edit the view in the browser and save it without making any changes to it!!
I'll post my entire code below for the benefit of anyone else trying to do something like this, but my question is: does anyone know of a change I can make in my code so that the [Today] parameter in the filter gets recognized correctly without having to edit and resave the view in the browser?
Code (the server url for the context is fake for privacy reasons, of course):
function runCode (){
//get the context of the site
var context = new SP.ClientContext('http://myserver.net/sites/wbt/SPS/MSP');
// attach a onRequestFailed function to the client context.
context.add_requestFailed(function (sender, args) {
alert('Request failed: ' + args.get_message());
});
//get all the views for a specific list present on the site
var viewCollection = context.get_web().get_lists().getByTitle("TestDocs").get_views();
//context.load(viewCollection);
console.log("viewCollection size: " + Object.keys(viewCollection).length);
//console.log(viewCollection);
// create a custom view ViewCreationInformation method.
// set view title and fields to be shown on the view
var createView = new SP.ViewCreationInformation();
createView.set_title("StaleContent");
var viewFields = ["Name","Modified", "Modified By"];
createView.set_viewFields(viewFields);
//build query
var camlQuery = new SP.CamlQuery();
var query = "<Where><Geq><FieldRef Name='Modified' /><Value Type='text'>[Today]-5</Value></Geq></Where>";
camlQuery.set_viewXml(query);
createView.set_query(camlQuery);
//add view to the collection and execute the query
viewCollection.add(createView);
context.load(viewCollection);
context.executeQueryAsync(function (){
var viewEnumerator = viewCollection.getEnumerator();
var viewCount = 0;
while (viewEnumerator.moveNext()){
//debugger;
var oview = viewEnumerator.get_current();
var currView = oview.get_objectData().get_properties();
console.log("Title:", currView.Title);
viewCount ++;
console.log("viewCount:",viewCount);
if(currView.Title==="StaleContent")alert("StaleContent view successfully created.");
} //end while
}); //end QueryAsync function
} //end runCode function
Value Type='DateTime'