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

Get content of Google Form response when submitting


I am trying to create a Google App Script to generate Google Doc that contains content of Google Form response (answer of question, uploaded image). Is it possible to do the following?

added the following after submitted

I want to know the answers of the following questions to implement this.

  1. how to trigger App script when form is submitted
  2. how to get form response object from triggered script

For the question 1, * We can manually install a trigger https://developers.google.com/apps-script/guides/triggers/installable#managing_triggers_manually * We can get form response objects like this

function onFormSubmit(e) {
  const form = FormApp.getActiveForm();
  const formResponses = form.getResponses();
  Logger.log('form id = ' + form.getId() + ', length = ' + formResponses.length);
  const formResponse = formResponses[formResponses.length-1];
  const itemResponses = formResponse.getItemResponses();

  const doc = DocumentApp.create('New response');
  const body = doc.getBody();

  for (var j = 0; j < itemResponses.length; j++) {
    var itemResponse = itemResponses[j];
    const item = itemResponse.getItem();
    body.appendParagraph('Response #%s to the question "%s" was "%s"',
        (i + 1).toString(),
        itemResponse.getItem().getTitle(),
        itemResponse.getResponse());
  }

  docblob = doc.getAs('application/pdf');
  docblob.setName(doc.getName() + ".pdf");
  const file = DriveApp.createFile(docblob);
  DriveApp.addFile(file);

  MailApp.sendEmail(
    "mail address",
    "new response",
    file.getDownloadUrl())
}

Solution

  • Triggers:

    First of all, you need to set up an onFormSubmit trigger.

    Mogsdad has a great answer for this:

    1. Choose Edit > Current project's triggers. You see a panel with the message No triggers set up. Click here to add one now.
    2. Click the link.
    3. Under Run, select the function you want executed by the trigger. (That's getResponse(), in this case.)
    4. Under Events, select From Spreadsheet.
    5. From the next drop-down list, select On form submit.
    6. Click Save.

    Note: The trigger needs to be set up on the spreadsheet for this.


    Get Response Values:

    Once you have your trigger set up properly, all you need is:

    function getResponse(e) {
      var response = e.values;
    }
    

    Here we're using event objects to get the values submitted in the form response. This returns the array of values being submitted to the spreadsheet, in the example I tested, the array looks like this:

    [25/07/2019 10:02:36, Option 1, Answer 2, Option 3]


    References: