Home > Software design >  creating subfolder when creating parent folder
creating subfolder when creating parent folder

Time:11-04

would it be possible to add in sub folders (with preset names) when creating a new folder via script

function createFolder() {
  const parent = DriveApp.getFolderById("1Cyki5N4HBaKWo7fs1Ye3PVjl8KeEdOPs");
  const sheet = SpreadsheetApp.getActive().getSheetByName('Detailing');
  const range = sheet.getRange(2, 1, sheet.getLastRow() - 2);
  range.getValues().forEach(function (row, index) {
    // Consider checking if this r & c has a formula in the equal size array from getFormulas()
    if(row[0]) {
      var newLink = getLinkForFolderName_(parent, row[0]);
      // Use the current array index to write this formula in only the correct cell.
      range.offset(index, 0, 1).setFormula(
        "HYPERLINK(\""   newLink   "\", \""   row[0]   "\")"
      );
    }
  });
}

function getLinkForFolderName_(root, name) {
  var folder;
  const search = root.getFoldersByName(name);
  if (search.hasNext()) {
    folder = search.next();
    if (search.hasNext())
      console.warn("Multiple folders named '"   name   "' in root folder '"   root.getName()   "'");
  }
  else {
  folder = root.createFolder(name);
  ["Quote", "Detailing", "Delivery"].forEach(function(e) {
    folder.createFolder(e);
  });
}
}

what I would like to happen is when the new parent folder is created, subfolders labelled Quote, Detailing, Delivery to be created at the same time

thank you for your help

CodePudding user response:

In your situation, how about modifying your script as follows?

From:

}
else
  folder = root.createFolder(name);

To:

} else {
  folder = root.createFolder(name);
  ["Quote", "Detailing", "Delivery"].forEach(function(e) {
    folder.createFolder(e);
  });
}
  • In this modification, using folder in your script, the subfolders with the folder names of "Quote", "Detailing", "Delivery" are created in folder.

  • From your script, I'm worried that you might disable V8 runtime. So I used forEach(function(e) {}). If you are using V8 runtime, you can also use the following script.

      ["Quote", "Detailing", "Delivery"].forEach(e => folder.createFolder(e));
    
  • Related