Search code examples
google-apps-script

What am I doing wrong with event objects in google apps script?


Maybe i'm misunderstanding how event objects work, but i've been following a tutorial on how to get google forms to send a pdf every time the form is submitted. This led me to the function onFormSubmit(e){ } and then pull e.namedValues, but it keeps giving me

TypeError: Cannot read properties of undefined (reading 'namedValues') onFormSubmit @ Code.gs:2

What am I not understanding that's leading me to do this wrong? I've got the trigger set up that when the form is submmited to run onFormSubit, but i just can't get it to use event objects.

function onFormSubmit(e) {
  const info = e.namedValues;
  createPDF(info);
}

function createPDF(info ){

const pdfFolder = DriveApp.getFolderById("1g58GUQLPjPonsHtxj5LlxyoDgXs5wj2R");
const tempFolder = DriveApp.getFolderById("1Fkzf0xeZcedfq7BF2k3V4mn4Pz_LsXsv");
const templateDoc = DriveApp.getFileById("1eOqom8SqhuDUpIqYEVum-EvQ09cVz2d_XCLcRNAz8jE");

const newTempFile = templateDoc.makeCopy(tempFolder);

const openDoc = DocumentApp.openById(newTempFile.getId());
const body = openDoc.getBody();
body.replaceText("{fn}", info['First Name'][0]);
body.replaceText("{ln}", info['Last Name'][0]); 
body.replaceText("{bd}", info['Birthday'][0]);
body.replaceText("{em}", info['Email'][0]);
body.replaceText("{pn}", info['Phone Number'][0]);
body.replaceText("{pv}", info['Province'][0]);
body.replaceText("{cm}", info['Contact Method'][0]);
body.replaceText("{lg}", info['Language'][0]);
body.replaceText("{ts}", info['Type Of Service'][0]); //error TypeError: Cannot read properties of undefined (reading '0')
body.replaceText("{cn}", info['Child Name'][0]);
body.replaceText("{cbd}", info['Child Birthday'][0]);
body.replaceText("{sr}", info['Services Required'][0]);
body.replaceText("{stf}", info['Staff Requested'][0]);
body.replaceText("{pri}", info['Priority'][0]);
body.replaceText("{ref}", info['Referral'][0]);
body.replaceText("{jc}", info['Jane Consent'][0]);

openDoc.saveAndClose();

const blobPDF = newTempFile.getAs(MimeType.PDF);
const pdfFile = pdfFolder.createFile(blobPDF).setName(info['First Name'][0] + ' ' + (info['Last Name'][0] ));
tempFolder.removeFile(newTempFile);

}

Solution

  • The error indicates that e is undefined, which means that you probably ran the function in the script editor. Don't run the code through the ▷ Run button in the script editor. If you do, the event parameter e won't be populated, causing the error you mention.

    Instead, let the trigger run the function when you submit a new form response.

    When the script project is bound to a spreadsheet, and the function runs when the "on form submit" trigger fires, e.namedValues will be present.

    For debugging, see How can I test a trigger function in GAS?