mardi 28 juillet 2020

Google Apps Script_populate multiple templates depending on google form data and then email pdf copies

Help greatly needed.

Using Google Form to gather data, in order to populate one of 2 Google doc templates, dependent on whether option 1 or 2 is chosen in the Google form. Populated template to be saved in "final" folder as a PDF, and then emailed to the email address submitted in the Google form.

Currently, I'm able to generate the correct PDF files in the correct folder and send the email to the correct address, but there is no attachment and just the words [Object object].

Before I included the if/else function, I was able to correctly send the email with attachment, which means that I've caused a problem with the if/else and naming of the generated pdfs. I just can't figure it out.

function autoFillGoogleDocFromForm(e) {
  //form values
  var timestamp = e.values[0];
  var firstName = e.values[1];
  var lastName = e.values[2];
  var email = e.values[3];
  var multiplechoice = e.values[4];

  if (multiplechoice == "Template 1") {
    //This section will complete template 1
    var file = DriveApp.getFileById("Template 1 ID");

    //Create copy of Template 1
    var folder = DriveApp.getFolderById("Templates folder ID")
    var copy = file.makeCopy(lastName + ',' + firstName, folder);

    //Open copy of Template 1 and replace key fields per form data
    var doc = DocumentApp.openById(copy.getId());
    var body = doc.getBody();
    body.replaceText('', firstName);
    body.replaceText('', lastName);
    doc.saveAndClose();
    Utilities.sleep(1500);
  } else {
    //This section will complete Template 2 by default
    var file = DriveApp.getFileById("Template 2 ID");

    //Create copy of Template 2
    var folder = DriveApp.getFolderById("Templates folder ID")
    var copy = file.makeCopy(lastName + ',' + firstName, folder);

    //Open copy of Template 1 and replace key fields per form data
    var doc = DocumentApp.openById(copy.getId());
    var body = doc.getBody();
    body.replaceText('', firstName);
    body.replaceText('', lastName);
    doc.saveAndClose();
    Utilities.sleep(1500);
  }

  //create pdf copy of completed template
  var pdffolder = DriveApp.getFolderById("Templates folder ID");
  var pdfFILE = DriveApp.getFileById(copy.getId()).getAs('application/pdf');
  pdfFILE.setName(copy.getName() + ".pdf");
  var theFolder = pdffolder;
  var theFile = DriveApp.createFile(pdfFILE);
  theFolder.addFile(theFile);
  Utilities.sleep(1500);

  var subject = "File attached";
  var attach = theFile;
  var pdfattach = attach.getAs(MimeType.PDF);

  MailApp.sendEmail(email, subject, {attachments: [pdfattach]});
  
  }

Aucun commentaire:

Enregistrer un commentaire