3
votes

I'm trying to set up a basic script that emails on form submission, with the (pie in the sky) goal of creating an email that will send an attached outlook calendar invite. Here is my script.

function onFormSubmit(e) {
  var userName = e.values[1];
  var userEmail = e.values[2];
  var subject = "Form Submitted";
  var message = "Thank you, " + userName + " for your submission";
  MailApp.sendEmail(userEmail, subject, message)
}

Here's an image of my trigger situation

The error I get is: "TypeError: Cannot read property "0" from undefined."

Here's an image of the Execution transcript

Here's where I've been: Google Scripts for Sheets - onEdit and "source"

I promise I'm not running in the editor - I'm filling out the form and submitting. I know I have to be doing something stupid, but I can't figure out what it is. Thanks for your help.

2
I'm guessing that your code is in a project bound to the Form? There is no values property of the event object sent to a script bound to the Form. If you set up the code to be in a project bound to a spreadsheet, then you can use the values property. If you don't want to use a script bound to a spreadsheet, you'll need to use e.response which gets a Form response. Apps Script documentation - Form response Then you'll need to get the values out of the Response.Alan Wells
You are guessing correctly. I tried to substitute "e.response" and (e.responses) for "e.values", but I got an undefined error - "Execution failed: TypeError: Cannot read property "1" from undefined. " I then moved the script over to the spreadsheet as opposed to the form, and the script worked. Is there a best practice as far as where the script should bound? Thanks so much for your help.DavidSM
I don't know of any best practice for this. I would mainly make the decision based on "ease of access" to whatever I need. For you, it's a lot easier to put the "On Form Submit" trigger into the spreadsheet.Alan Wells

2 Answers

3
votes

Your "On Submit" trigger is running from a script bound to the Form, and the values property is not available to the event object sent to the Form. The values property is only available to the event object sent to the spreadsheet.

See Event Objects:
Event Objects

1
votes

In order to access the form submission properties, you need to treat your event object e as a FormResponse object.

https://developers.google.com/apps-script/guides/triggers/events#form-submit_1

function onFormSubmit(e) {
  var responses = e.response.getItemResponses();
  for( var i=0; i < responses.length; i++ ) {
    console.log(responses[i].getItem().getTitle() + " : " + responses[i].getResponse());
  }
}