cy6581
cy6581

Reputation: 153

Embedding onFormSubmit Triggers for multiple Google forms that I generate with Script

I have a script for creating multiple Google forms. within each Google form, I want to create an onFormSubmit trigger to post the responses to a selected spreadsheet.

Using installable triggers but the trigger doesn't seem to get embedded into the forms I create. The code as follows:

for(i = 0; i<arrayOfArrays.length; i++) {
    var form = FormApp.create("Name");
    form.setTitle('Blah blah');

    form.addTextItem();
    // my questions

   function writeToSpreadsheet() {
     var formResponses = form.getResponses();
     var ss = SpreadsheetApp.getSpreadsheetByName("1bFjwHt_8Ct_iJCDc5F3lFgrCqSTMjQVOHrL3DQEzLmM");
     var sheet = ss.getSheets()[0]; 
     var newRow = sheet.getLastRow() + 1;

     for (j=0; j<array.length; j++) {
       var questionResponse = formResponses[j];
       ss.getRange(newRow,j+1).setValue(questionResponse);
     }
   }// end writeToSpreadsheet

  function createFormSubmitTrigger() {
     ScriptApp.newTrigger(writeToSpreadsheet)
           .forForm(form)
           .onFormSubmit()
           .create();
  }

}// ends loop to create many forms

Am I doing it right, or is this not even possible? Thanks!

Upvotes: 0

Views: 415

Answers (1)

Riyafa Abdul Hameed
Riyafa Abdul Hameed

Reputation: 7983

  • One thing to note is that you cannot create a function inside a for loop but you can call the function.
  • Second thing is that a trigger does not fire unless you have authorized the script that is you need to manually run the trigger function for every form to get it to work
  • You need to manually install each script to each form or you can install the script in one form and copy the form and the script would be installed in the copied form but you need to run the trigger once to authorize it.

Your script is error prone because functions cannot be defined inside another function let alone a for loop.

Upvotes: 0

Related Questions