none
Run Javascript code to Create Folders when Item is added to a List -REST SharePoint RRS feed

  • Question

  • Hi i have a simple code to create folders in a sharePoint Library. But i am trying to adapt the code to only create a folder when an item has been added to a specific SharePoint list.

    So as soon as a user clicks save button on the newform page on the list. the javascript code runs picking the item title as foldername to be created in the specified library.

    Any help will be appreciated

    thanks

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script>
    
    <script type="text/javascript">
    
    
    //list users will add items into
    var getRecentItemCountries = function () {  
    
              var requestURL =  _spPageContextInfo.webAbsoluteUrl +
                         "/_api/Web/Lists/getByTitle('State')/items?$select=Title";
    
                $.ajax({  
                    url: requestURL,  
                    method: "GET",  
                    headers: { "Accept": "application/json; odata=verbose" },  
                    success: function (data) {  
                        console.log(data);
                                            //success(data); 
    
                    },  
                    error: function (data) {  
                        //failure(data);  
                    }  
                });  
            }
    
            var createfolder = function (ListItemName) {  
    
            var documentLibraryName = 'AppLogos';
            var ListItemName = 'test';
    
              
    
             var fileCollectionEndpoint = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfolderbyserverrelativeurl('" + documentLibraryName + "')/folders/add(url=\'" + ListItemName + "\')";
    
                $.ajax({  
                    url: fileCollectionEndpoint,  
                    method: "POST",
                    //body: { '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '/AppLogos/test'},  
                    headers: { "X-RequestDigest":  window.top.$("#__REQUESTDIGEST").val(), "Accept": "application/json;odata=verbose", "content-type": "application/json;odata=verbose"  },
                    success: function (data) {  
                        console.log(data);
                                            //success(data); 
                                            console.log("Folder creted succesfully");
                                            //alert(‘Folder created successfully’);
    
                    },  
                    error: function (data) {  
                        //failure(data);  
                    }  
                });  
            }
    
            $(document).ready(function (){
    
                getCountries();
    
                createfolder();
            })
    
    
    
    
    </script>


    • Edited by dongotti Friday, January 6, 2017 1:49 PM
    Friday, January 6, 2017 11:55 AM

Answers

  • Hi,

    The following articles for your reference, add the code below into a content editor web part or Script editor web part into the new item page.

    <script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    function getFormDigest() {
        return $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo",
            method: "POST",
            headers: { "Accept": "application/json; odata=verbose" }
        });
    }
    
    function PreSaveItem() {	 
    	var folderName=$("input[title='Title Required Field']").val(); //get new list item title
    	if(folderName!=""){
    		createfolder(folderName).done(function (data) {
    			console.log('Folder creted succesfully');
    		}).fail(function (error) {
    			console.log(JSON.stringify(error));
    		});		
    	}
    	return true;
    }
    function createfolder(folderName){
    	var documentLibraryName = "AppLogos";
    	var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/folders";
    	return getFormDigest().then(function (data) {
    		return $.ajax({
    			url: requestUri,
    			type: "POST",			
    			contentType: "application/json;odata=verbose",
    			data:JSON.stringify({'__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': documentLibraryName+'/'+folderName}),
    			headers: {
    				"accept":"application/json;odata=verbose",			 
    				"X-RequestDigest":data.d.GetContextWebInformation.FormDigestValue
    			} 
    		});
        });
    }
    </script>

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    • Marked as answer by dongotti Monday, January 9, 2017 10:08 AM
    Monday, January 9, 2017 7:14 AM
    Moderator

All replies

  • Hi,

    Try this code

    var newFolder = 'DocumentLibrary/'+$('#TitleField).val()+')
    var pCreate = jQuery.ajax({
    "url"        : _spPageContextInfo.siteAbsoluteUrl + "/_api/Web/Folders/add(newFolder)",
    "type"       : "POST",
    "headers"    : { 
                    "accept"          : "application/json; odata=verbose", 
                    "content-type"    : "application/json; odata=verbose",
                    "X-RequestDigest" : $("#__REQUESTDIGEST").val()
                   }
    }); 
    
    jQuery.when(pCreate).always(function (data){
       console.log(data);
    });


    Murugesa Pandian | MCPD | MCTS | SharePoint 2010 |


    Friday, January 6, 2017 6:13 PM
  • Thanks Murugesa,i'm struggling to understand how your code works... i dont see any reference to any other list. it seems your code creates a folder on pageload, or am i missing something.

    i'm try to achieve a situation when i add an item to a particular list a folder is created in seperate library. would it be okay for you to explain how your code achieves this.

    thanks so much for your help 

    Saturday, January 7, 2017 6:31 AM
  • Hi,

    You need to grab the value (variable newFolder) of text using jQuery and pass to ajax call. you can wrap all this code under PreSaveAction button click.

    Please refer this link on how to wire up the above code in presave action.

    http://www.enjoysharepoint.com/Articles/Details/presaveaction-in-newform-aspx-in-sharepoint-2013-21106.aspx


    Murugesa Pandian | MCPD | MCTS | SharePoint 2010 |



    Saturday, January 7, 2017 7:32 AM
  • Hi,

    The following articles for your reference, add the code below into a content editor web part or Script editor web part into the new item page.

    <script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    function getFormDigest() {
        return $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo",
            method: "POST",
            headers: { "Accept": "application/json; odata=verbose" }
        });
    }
    
    function PreSaveItem() {	 
    	var folderName=$("input[title='Title Required Field']").val(); //get new list item title
    	if(folderName!=""){
    		createfolder(folderName).done(function (data) {
    			console.log('Folder creted succesfully');
    		}).fail(function (error) {
    			console.log(JSON.stringify(error));
    		});		
    	}
    	return true;
    }
    function createfolder(folderName){
    	var documentLibraryName = "AppLogos";
    	var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/folders";
    	return getFormDigest().then(function (data) {
    		return $.ajax({
    			url: requestUri,
    			type: "POST",			
    			contentType: "application/json;odata=verbose",
    			data:JSON.stringify({'__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': documentLibraryName+'/'+folderName}),
    			headers: {
    				"accept":"application/json;odata=verbose",			 
    				"X-RequestDigest":data.d.GetContextWebInformation.FormDigestValue
    			} 
    		});
        });
    }
    </script>

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    • Marked as answer by dongotti Monday, January 9, 2017 10:08 AM
    Monday, January 9, 2017 7:14 AM
    Moderator
  • Thanks  so much Dennis, it works when i just insert code .

    But to help my understanding about how the code works. it feels like i'm missing something, i don't see anywhere on the code where there is a function. So i confused me as to where the code actually does start.

    So i know the Createfolder function is called from the Presaveitem function, but i dont see where the getFormDigest function is called or the presaveItem function is called.

    Also What does the getFormDigest function do? and why & when (or in what instances ) would you need to use it.

    Monday, January 9, 2017 8:59 AM
  • Hi,

    PreSaveItem is a Out-of-the-box method, please check the blog below:

    http://blog.riccardocelesti.it/using-presaveitem-to-add-custom-validation-to-sharepoint-list-form/

    When creating, updating, and deleting SharePoint entities is that if you aren’t using OAuth to authorize your requests, these operations require the server’s request form digest value as the value of the X-RequestDigest header. You can retrieve this value by making a POST request with an empty body to http://<site url>/_api/contextinfo and extracting the value of the d:FormDigestValue node in the XML that the contextinfo endpoint returns.

    More information is here: https://msdn.microsoft.com/en-us/library/office/jj164022.aspx

    If my reply helps you, please mark the reply as answer, it will make others who stuck with the similar issue easier to search for valid solutions in this forum.

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com


    Monday, January 9, 2017 9:10 AM
    Moderator
  • Thanks a lot for your help.
    Monday, January 9, 2017 10:08 AM