google-apps-scriptgoogle-sheetstriggersgoogle-forms

Form title from FormResponse


I have created a bunch of forms programmatically from a spreadsheet and bound a response trigger to each. When a form is filled out I can't seem to figure out which form was completed.

I tried:

Event.source.getId() 

But that returns the id of the spreadsheet. I want to get the title of the form.

Edit: Clarification

This is how I set up the trigger:

ScriptApp.newTrigger('responseTrigger').forForm(form)
 .onFormSubmit()
 .create();

And when I try to get the title:

function responseTrigger(e) {
  var source = e.source;
  var title = e.source.getTitle().
  Logger.log(title);
}

I get the following error:

Execution failed: TypeError: Cannot find function getTitle in object Spreadsheet.


Solution

  • I have finally solved this issue.

    There is a known Google Scripts issue that is causing my problem. You would expect e.source.getID() to give you the form's ID, however it gives you the spreadsheet's ID. I found a solution in this question. What you do is find the unique ID of the trigger and cross reference it with all of the project triggers as follows:

        function getFileByTriggerId(triggerId){
          var triggers = ScriptApp.getProjectTriggers();
          for(var i =0; i<triggers.length; i++){
           if(triggers[i].getUniqueId() == triggerId){
            return triggers[i].getTriggerSourceId();
        }
      }
    }
    

    And then in your response trigger you write:

    function responseTrigger(e) {
      var realEvent = getFileByTriggerId(e.triggerUid);
      var form = FormApp.openById(realEvent);
      var title = form.getTitle();
    }