Create SharePoint List/Library using JSOM (JavaScript)
Use the below code to create a SharePoint document library using REST API. You can change the 'set_templateType' value for creating list/library based on your requirement.
//Create library using JSOM
function createNewLibraryUsingJSOM()
{
var newListName = "Your New List/Library Name here";
SP.SOD.executeFunc('SP.js', 'SP.ClientContext',
function() {
//get site details
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var clientContext = new SP.ClientContext(siteUrl);
web = clientContext.get_web();
//create list object for new list
var listCreationInfo = new SP.ListCreationInformation();
listCreationInfo.set_templateType(SP.ListTemplateType.documentLibrary); //SP.ListTemplateType.announcements
listCreationInfo.set_title(newListName);
listCreationInfo.set_quickLaunchOption(SP.QuickLaunchOptions.on);
//get all lists & insert new list into it
var lists = web.get_lists();
list = lists.add(listCreationInfo);
//call async method
clientContext.load(list);
clientContext.executeQueryAsync(onSuccess, onError);
});
}
function onSuccess(){
var result = list.get_title() + ' created.';
alert(result);
}
function onError(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
//Create library using JSOM
function createNewLibraryUsingJSOM()
{
var newListName = "Your New List/Library Name here";
SP.SOD.executeFunc('SP.js', 'SP.ClientContext',
function() {
//get site details
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var clientContext = new SP.ClientContext(siteUrl);
web = clientContext.get_web();
//create list object for new list
var listCreationInfo = new SP.ListCreationInformation();
listCreationInfo.set_templateType(SP.ListTemplateType.documentLibrary); //SP.ListTemplateType.announcements
listCreationInfo.set_title(newListName);
listCreationInfo.set_quickLaunchOption(SP.QuickLaunchOptions.on);
//get all lists & insert new list into it
var lists = web.get_lists();
list = lists.add(listCreationInfo);
//call async method
clientContext.load(list);
clientContext.executeQueryAsync(onSuccess, onError);
});
}
function onSuccess(){
var result = list.get_title() + ' created.';
alert(result);
}
function onError(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
Comments
Post a Comment