//Author: Shantha Kumar T
//Method used: SP.List.saveAsNewView( oldView, newName, privateView, uri) (SP.js)
//Paramteres:
////oldView: Guid of the view
////newName: Name for the new view
////privateView: Boolean value to set private view or public view
////uri: url for new view
//Supports: SharePoint 2013 + and SharePoint Online
function CreateDuplicateView(listTitle, oldView, newView) {
var clientContext = new SP.ClientContext();
oList = clientContext.get_web().get_lists().getByTitle(listTitle);
//The below method used to create a new view based on old view in the list
oList.saveAsNewView(oldView, newView, false, "duplicateview.aspx");
var newViewValue = oList.get_views().getByTitle(newView);
clientContext.load(newViewValue);
clientContext.executeQueryAsync(
Function.createDelegate(this, function() {
var successInfo = '';
successInfo += newViewValue.get_title() + " view duplicated successfully";
//console.log(successInfo.toString());
alert(successInfo.toString());
}),
Function.createDelegate(this, function(sender, args) {
//console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}));
}
function injectMethod() {
var lisTitle = "ListName";
var strviewGuid = "59A88256-510F-4C66-836E-E91C6D30A73A";
var strnewViewTitle = "Duplicate View";
//SP.Guid.isValid method used to validate the GUID and returns the boolean value
if (SP.Guid.isValid(strviewGuid)) {
CreateDuplicateView(lisTitle, new SP.Guid(strviewGuid), strnewViewTitle);
} else {
alert("Provided GUID is not a valid one!");
}
}
ExecuteOrDelayUntilScriptLoaded(injectMethod, "sp.js");This code snippet has the example to create a new based on old view in a SharePoint List using JSOM.
