Search code examples
google-apps-scriptgoogle-sheetsgoogle-forms

Automatically save form in folder


I wrote a script in Google Apps Script that creates new forms from Google Sheets. How can I save the form automatically in a specific folder in the drive?


Solution

  • You don't say, but let's assume you're creating a Google Form, e.g. like this:

    var form=FormApp.create('My form');
    

    In that case, here's a function that will add the Drive File of that form to a Drive Folder that you specify. Note - this function can support Documents, Spreadsheets, and other file types... any Google Apps Script object that has a getId() method and can also be represented as a Drive File.

    /**
     * Places file for given item into given folder.
     * If the item is an object that does not support the getId() method or
     * the folder is not a Folder object, an error will be thrown.
     * From: http://stackoverflow.com/a/38042090/1677912
     *
     * @param {Object}  item     Any object that has an ID and is also a Drive File.
     * @param {Folder}  folder   Google Drive Folder object.
     */
    function saveItemInFolder(item,folder) {
      var id = item.getId();  // Will throw error if getId() not supported.
      folder.addFile(DriveApp.getFileById(id));
    }
    

    Example:

    // Create temporary form 
    var form=FormApp.create('Delete me');
    // Get temporary folder
    var folder=DriveApp.getFoldersByName('Delete me').next();
    
    saveItemInFolder(form,folder);