Introduction
This article explains how to create a folder in a Document Library in SharePoint 2013 using CSOM-JavaScript.
Prerequisites
- Ensure you have access to the Office 365 online.
- Ensure Napa Tools is available in your site.
Use the following procedure:
- Create an app for SharePoint using Office 365 Tools. If you have missed out on how to create an app in SharePoint 2013, then Click here.
- Create a Document Library and name it “MyDocumentLibrary”. Refer to my article if you want to learn how to create a Document Library in SP2013.
- Click on the Default.aspx page.
- Add a button to create a folder and place it inside the “PlaceHolderMain” tag.
<button id="btnCreateFolder" onclick="createFolder()">Create Folder</button><br/>
- Click on the App.js file.
- Globally declare the content, web and list object as shown below.
var context = SP.ClientContext.get_current(); //gets the current context
var web = context.get_web(); //gets the web object
var list = web.get_lists(); //gets the collection of lists
var targetList;
var itemCreation;
- Now write the function to create a folder in a Document Library:
function createFolder() {
targetList = list.getByTitle("MyDocumentLibrary");
itemCreation = new SP.ListItemCreationInformation();
itemCreation.set_underlyingObjectType(SP.FileSystemObjectType.folder);
itemCreation.set_leafName("MyCustomFolder");
var folderItem = targetList.addItem(itemCreation);
folderItem.update();
context.load(folderItem);
context.executeQueryAsync(onFolderCreationSuccess, onFolderCreationFail);
}
- Here in this example we are creating a folder using the “ListItemCreationInformation” object.
- After creating the listitem object we need to set the underlyingObjectType as a folder and leafname represents the folder name.
- Add the ListItemCreationInformation object to the list using the additems method and assign it to an item object.
- Then we need to load the new item object and execute the code by calling executeQueryAsync ().
function onFolderCreationSuccess() {
alert("Folder Created");
}
function onFolderCreationFail(sender, args) {
alert('Failed to Create the Folder. Error:' + args.get_message());
}
- That's it. Now let's start testing.
Testing
- Now to run the app click on the "Play" button that is available towards the left-most corner.
- The app is packaged, deployed, and installed on your Office 365 Site.
- Now you will be able to see the following page. Now click on the Create Folder Button.
- To see the folder, that was recently created, just go to the following URL:
Syntax: https://yoursite/DocumentLibraryName
Example: https://mysite/MyDocumentLibrary
Summary
Thus in this article you saw how to create a folder in a Document Library in SharePoint 2013 using CSOM-JavaScript.