0
votes

I'm trying to create a script that sends an email when someone submits a google form. The form includes an optional file upload that the script will then attach to the email as a pdf.

The issue I'm facing is how to ignore the process that creates the attachment if the response is empty.

Sample code below

function getIdFrom(url) {
  var id = '';
  var parts = url.split(
    /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/
  );
  if (url.indexOf('?id=') >= 0) {
    id = parts[6].split('=')[1].replace('&usp', '');
    return id;
  } else {
    id = parts[5].split('/');
    var sortArr = id.sort(function (a, b) {
      return b.length - a.length;
    });
    id = sortArr[0];
    return id; //returns google doc id.
  }
}

function onFormSubmit(response) {
  var link = response.namedValues['Upload file'];

  if (typeof link !== "undefined" && link.length > 0) { // I think it's here that's the issue
    var uploadFileId = getIdFrom(link[0]);
    var uploadFile = DriveApp.getFileById(uploadFileId);
    var uploadFileType = (function () {
      if (uploadFile.getMimeType().includes('image')) {
        return uploadFile.getMimeType();
      } else {
        return 'application/pdf';
      }
     };
    var attachArr = [uploadFile.getAs(uploadFileType)];
  } 
  // etc etc send email.
}

Works fine if the user submits a form with an uploaded file.

However if the form is submitted without entering anything in the "Upload File" question, I'm getting a "TypeError: Cannot read property 'split' of undefined" at the getIdFrom(url) function I assume because it's still trying to pass link through getIdFrom() even though it shouldn't because it's undefined.

Weirdly it works perfectly fine when I use the two test inputs I have, one of which 'Upload File' exists but is empty and the other it doesn't exist at all.

I'm not sure what I'm missing here.

Also I have no doubt it's a messy way to do things but I'm getting there.

1

1 Answers

0
votes
  • response.namedValues['Upload file'] is an object

  • even if it's empty it will have at least the length of >0

Workaround

Modify your if statement to

if (link[0].length > 0) { 
  ...
}