简体   繁体   中英

How to get Google script trigger to fire automatically (works manually) when creating a new folder

I created a script to create a new folder every time a form is submitted. The point of the script was to put each newly created folder in a specific parent folder determined by a column value on a spreadsheet (new values are generated when forms are submitted). At the moment the script does not fire automatically even though a trigger event is setup, but will fire and create the new folder in the proper location when manually run. Any help would be appreciated.

function createNewFolder() {

    // identify the sheet where the data resides 
    var ss = SpreadsheetApp.getActive();
    var names = ss.getSheetByName("Form Responses 1");
    var ids = ss.getSheetByName("Form Responses 1");

    //identify the cell that will be used to name the folder  
    var getName = names.getRange(names.getLastRow(), 3).getValue();

    //identify the cell that determines which parent folder to use
    var folderId = ids.getRange(ids.getLastRow(), 5).getValue();

    //identify the parent folder the new folder will be in 
    var parentFolder = DriveApp.getFolderById(folderId);

    //create the new folder 
    var newFolder = parentFolder.createFolder(getName);

}

The trigger fails about 85% of the time and is setup to fire when a new form response is logged on the associated spreadsheet.

Try replacing your onFormSubmit function with this:

This function should be created in the spreadsheet that has the linked sheets. This function utilizes the data that is sent in the form submit event object. Don't forget to include the 'e' in the function as a parameter.

function createNewFolder(e) {
  var parentFolder = DriveApp.getFolderById(e.values[4]);
  var newFolder = parentFolder.createFolder(e.values[2]);
}

Also you may want to look at this question since we have been seeing a lot of problems with spurious form submit triggers. If you don't need to implement it fine but it might be something to consider.

It's most likely an async issue. The parentFolder.createFolder function probably is getting called before the parentFolder is done fetching data from DriveApp. Try this:

var newFolder = parentFolder.then(() => {
    parentFolder.createFolder(getName)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM