Search code examples
arraysgoogle-apps-scriptgoogle-sheetsgmailgoogle-forms

Creating and Emailing Totals Doc from Google Form Responses


I am trying to create a function that takes form response data and applies it to a template to create a 'completion certificate' with their total scores, then emails them a link to it.

On the certificate, their answers are split into four groups, but I am having trouble creating totals for the each of the answer arrays.

Here is my current code:

 function autoFillGoogleDocFromForm(e) {
  var timestamp = e.values[0];
  var firstName = e.values[1];
  var lastName = e.values[2];
  var emailAddress = e.values[3];

  var disbeliefScore = e.values[4,5,6,7,8].reduce((a, b) => a + b, 0);
  var discomfortScore = e.values[9,10,11,12,13].reduce((a, b) => a + b, 0);
  var explorationScore = e.values[14,15,16,17,18].reduce((a, b) => a + b, 0);
  var acceptanceScore = e.values[19,20,21,22,23].reduce((a, b) => a + b, 0);
  
  var file = DriveApp.getFileById("fileIdGoesHere"); 
  
  var folder = DriveApp.getFolderById("FolderIdGoesHere")
  
  var copy = file.makeCopy(lastName + ',' + firstName, folder); 
  
  var doc = DocumentApp.openById(copy.getId()); 
  
  var body = doc.getBody(); 
  
  body.replaceText("{{disbeliefscore}}", disbeliefScore);
  body.replaceText("{{discomfortscore}}", discomfortScore);
  body.replaceText("{{explorationscore}}", explorationScore);
  body.replaceText("{{acceptancescore}}", acceptanceScore); 
  
  doc.saveAndClose();

  var url = doc.getUrl();

  MailApp.sendEmail(emailAddress, "Your Leading Change Questionnaire Results Link",{from:"alternative email address to go here", name:"Alternative Name to go here"},url)

 }

The code mostly works (replacing text and sending the email), but the replaced text only seems to be the first value of the group, rather than the total.

For example this section:

var disbeliefScore = e.values[4,5,6,7,8].reduce((a, b) => a + b, 0);

is essentially behaving as:

var disbeliefScore = e.values[4];

and ignores the other values and the 'reduce' script.

As a side note, although the emails are being sent, the subject line of the email is coming out as [object Object].

Any help on either of these issues would be appreciated.

Thanks


Solution

  • Issue:

    The syntax Array[index] can be used to access a single element in the array. You cannot select multiple indexes from an array by using:

    e.values[4,5,6,7,8]
    

    Solution:

    In order to retrieve a chunk of the array, use slice:

    e.values.slice(4,9)
    

    Reference: