Google form spreadsheet update script - google-apps-script

I have some code for my form that works well for emailing the manager of an expense report for approval, as well as receiving a URL back with information needed to send the response back to the person who filled out the information on the form.
all i need it to do now is to update the field in the form with the proper approval message (accept or reject)
I think this will have to happen in the doGet method, but will I have to pass in more then just the row number and approval message to get this done? (e.g. getting the spreadsheet, getting the sheet, etc.)
here is what i have so far, both emails, and the URL generated appear to be correct:
function sendEmail(e){
/**
var email = e.values[1];
var item = e.values[2];
var cost = e.values[3];
*/
var serviceInformation = e.values[1];
var language = e.values[2];
var meetingType = e.values[3];
var eventDate = e.values[4];
var clientName = e.values[5];
var detailedDirections = e.values[6];
var onSitePOCName = e.values[7];
var onSitePOCNumber = e.values[8];
var department = e.values[9];
var contactPhoneNumber = e.values[10];
var approval = e.values[11]; //the one we need to modify
var requestorEmail = e.values[12];
var managerEmail = e.values[13];
var Language2 = e.values[14];
var interpreterName = e.values[15];
var interpreterAgency = e.values[16];
var dateConformationSent = e.values[17];
var specialNotes = e.values[18];
var row = e.range.getRow();
var url = 'https://script.google.com/a/macros/richmond.k12.va.us/s/AKfycbwuRr1boKTH0v1mprWmc7PE66_mQ_dmPE0lyWb7vkfiyW3pn31b/exec';
//add on the parameters to URL to send to the manager
var approve = url + '?approval=true'+'&reply='+requestorEmail+'&row='+row;
var reject = url + '?approval=false'+'&reply='+requestorEmail+'&row='+row;
var html = "<HTML><body>"+
"<h2>please review</h2><br />"
+"<P>" + language +" " + serviceInformation
+"<p>" + meetingType+ " on "+ eventDate + " for " +clientName
+"<p>" + "Location: "+ department
+"<p>" + "requester: "+ requestorEmail+ " "+
"<p>"+
"Approve<br />"+
"<p>"+
"Reject<br />"+
"</HTML></body>";
MailApp.sendEmail(managerEmail, "Approval Request", "what no html?", {htmlBody: html});
}
function doGet(e){
var params = JSON.stringify(e);
return HtmlService.createHtmlOutput(params);
//added in an edit
var id = '1UzlJ6Uw12H5dGVcLz7ONp3Neehq1DL21hqZnrMx7mxs';
var ss = SpreadsheetApp.openById(id);
var sheet = ss.getActiveSheet();
var column = 12;
var row = e.parameter.row;
var approval_cell = sheet.getRange(row, column);
Logger.log(row);
Logger.log(ss);
Logger.log(sheet);
Logger.log(approval_cell);
//logger logs the proper row. SS = Spreadsheet, sheet = sheet, approval_cell = Range
var aprovalResponce = (e.parameter.approval == 'true') ? 'Approved.' : 'Sorry, you need to reschedule';
//added values after aprovalResponce, in the email, they are both undefined.
var msg = "Your manager said : " + aprovalResponce;
var replyEmail = e.parameter.reply;
//MailApp.sendEmail(replyEmail, "Approval Request", msg);
//update the approval field
//changed in edit
if (e.parameter.approval == 'true') {
approval_cell.setValue("APPROVED"+;
} else {
approval_cell.setValue("DENIED");
}
//send the actual email out
MailApp.sendEmail(replyEmail, "Approval Request", msg);
}

It looks like you're trying to change the approval value in the spreadsheet? If so, I imagine this should work:
//update the approval field
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var column = 12;
var row = e.parameter.row;
var approval_cell = sheet.getRange(row, column);
if (e.parameter.approval == 'true') {
approval_cell.setValue("APPROVED");
} else {
approval_cell.setValue("DECLINED");
}

Related

on form submit trigger giving weird results

I have a script that creates forms that need to be filled out for ordering, the onformsubmittrigger places this weird line of text when it comes to the multi choice option [Ljava.lang.Object;#7c2a6e46, if possible I would also like to define where the answer are placed instead of the default of column a,b,c
function snore() {
var sheet = SpreadsheetApp.getActive().getSheetByName('TC');
var value = sheet.getRange("B2").getValue();
var em = sheet.getRange("C2").getValue();
var cos = sheet.getRange("F2").getValue();
var name = sheet.getRange("E2").getValue();
var sup = sheet.getRange("D2").getValue();
var form = FormApp.create(value);
var item = form.addMultipleChoiceItem();
item.setHelpText("Name: " + name +
"\n\nEmail: " + em +
"\n\nQuote No: " + value +
"\n\nProject: " + sup +
"\n\nTotal Cost: " + cos +
"\n\nBy selecting approve you agree to the cost and timeframe specified by the quote and that the details above are correct")
.setChoices([item.createChoice('Approved'), item.createChoice('Denied')]);
var itm = form.addCheckboxItem();
itm.setTitle('What extras would you like to add on? (all prices are Ex-GST)');
itm.setChoices([
itm.createChoice('Watergate Plus 1370mm x 36.5m, 36.5Lm - $109.80'),
itm.createChoice('Watergate Plus 2740mm x 30m, 30Lm - $171.60'),
itm.createChoice('White General Purpose Repair Tape 60mm x 66m, 66Lm - $39.21'),
itm.createChoice('Wall Wrap, Foil Fasteners, 500/box - $39.21'),
itm.createChoice('Super Course 500, 300mm x 0.5 x 50Lm - $29.30'),
itm.createChoice('40mm Metal Top Hat Batten - 3.10/mtr')
])
.showOtherOption(true);
Logger.log('Published URL: ' + form.getPublishedUrl());
Logger.log('Editor URL: ' + form.getEditUrl());
Logger.log('ID: ' + form.getId());
var myDId = DriveApp.getRootFolder().getId();
var rootFolder = DriveApp.getFolderById(myDId);
var archiveFolder = DriveApp.getFolderById("1Rt6xikEpHs-F2cQOTRrvATCZHCFU0bQ6");
var newForms = rootFolder.getFilesByName(value);
while (newForms.hasNext()) {
var newForm = newForms.next();
archiveFolder.addFile(newForm)
rootFolder.removeFile(newForm);
}
//const spreadsheetId = SpreadsheetApp.getActive().getId();
//form.setDestination(FormApp.DestinationType.SPREADSHEET, spreadsheetId);
SpreadsheetApp.getActiveSheet().getRange('J2').setValue('SENT');
var id = "1uw8HAJsuNHses_9XGfNtQ71fp3DXE7q1";
var buildBlob = DriveApp.getFileById(id).getBlob().setName("buildBlob");
var SendTo = "Jonathon.banks#westal.com.au";
var link = form.getId();
var message = "Please follow the link to accept you Quotation " + form.getPublishedUrl();
//set subject line
var body = HtmlService.createTemplateFromFile("email");
body.order = value;
body.overdue = form.getPublishedUrl();
var con = sheet.getRange("A2").getValue();
var file = DriveApp.getFilesByName(con).next()
var Subject = 'Quote' + value + 'Confirmation';
const recipient = em;
const subject = "Confirmation of order"
MailApp.sendEmail({
to: recipient,
attachments: file,
subject: subject,
htmlBody: body.evaluate().getContent(),
inlineImages:
{
build: buildBlob
}
});
//const subect = "confirm for id"
//const rcipient = SendTo;
//var mssage = "please run id confirm " + link;
//GmailApp.sendEmail(rcipient, subect, mssage)
const SOURCE_FORM_ID = link; // Change according to your needs
{
const form = FormApp.openById(SOURCE_FORM_ID);
ScriptApp.newTrigger("onFormSubmitTrigger")
.forForm(form)
.onFormSubmit()
.create();
}
var ss = SpreadsheetApp.getActiveSpreadsheet();
var seet = ss.getSheetByName('TC'); //source sheet
var testrange = seet.getRange('J:J'); //range to check
var testvalue = (testrange.getValues());
var csh = ss.getSheetByName('C'); //destination sheet
var data = [];
var j =[];
//Condition check in H:H; If true copy the same row to data array
for (i=0; i<testvalue.length;i++) {
if ( testvalue[i] == 'SENT') {
data.push.apply(data,seet.getRange(i+1,1,1,25).getValues());
//Copy matched ROW numbers to j
j.push(i);
}
}
//Copy data array to destination sheet
csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
//Delete matched rows in the source sheet
for (i=0;i<j.length;i++){
var k = j[i]+1;
sheet.deleteRow(k);
//Alter j to account for deleted rows
if (!(i == j.length-1)) {
j[i+1] = j[i+1]-i-1;
}
}
}
//const TARGET_SPREADSHEET_ID = "1JRhCnS048fhWMifkrD1mqdgFcs3-Cw-kGOzSgpLWfI0"; // Change according to your needs
//const TARGET_SHEET_NAME = "C"; // Change according to your needs
function onFormSubmitTrigger(e) {
const targetSpreadsheet = SpreadsheetApp.openById("1JRhCnS048fhWMifkrD1mqdgFcs3-Cw-kGOzSgpLWfI0");
const targetSheet = targetSpreadsheet.getSheetByName("C");
if (targetSheet.getLastRow() === 0) { // Add headers if they don't exist yet
const itemTitles = e.source.getItems().map(item => item.getTitle()); // Get item titles
itemTitles.unshift("Timestamp"); // Append "Timestamp" to the sheet (if desired)
targetSheet.appendRow(itemTitles); // Append form item titles to the sheet
}
const itemResponses = e.response.getItemResponses();
const responses = itemResponses.map(itemResponse => itemResponse.getResponse()); // Get user responses
responses.unshift(new Date()); // Add today's date to the responses (if desired)
targetSheet.appendRow([JSON.stringify(responses)])
}

Email not sending or probably not being triggered on form submit Google Apps Scripts

Well we have this google form and the details are being added to google sheet with custom g apps scripts. When the details have been appended to the google sheet log, it should send email. If I run the sendmail() manually, it works but when I call it inside onFormSubmit(), it's not working. What could have gone wrong?
function onFormSubmit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var templateLink = sheet.getSheetByName("Template Link").getRange(1, 1).getValue();
var logSheet = sheet.getSheetByName("Log");
var formResponsesSheet = sheet.getSheetByName("Form Responses 1");
var formResponsesHeader = formResponsesSheet.getRange(1, 2, 1, formResponsesSheet.getLastColumn() -1).getValues();
var newFileName = e.namedValues['Name'][0] + "-" + e.namedValues['Date'][0];
var populatedDocsFolder = DriveApp.getFolderById("1yTSd7W0U4Gcsm6CIw8NtD022F-MA7CPx");
var templateDocID = DocumentApp.openByUrl(templateLink).getId();
var newDocID = DriveApp.getFileById(templateDocID).makeCopy(newFileName, populatedDocsFolder).getId();
var newDocLink = DriveApp.getFileById(newDocID).getUrl();
var newDoc = DocumentApp.openById(newDocID);
var newDocBody = newDoc.getBody();
for (i = 0; i < formResponsesHeader[0].length; i++) {
var thisHeader = formResponsesHeader[0][i];
var thisValue = e.namedValues[thisHeader][0];
newDocBody.replaceText("<<" + thisHeader + ">>", thisValue);
}
//Log
var name = e.namedValues['Name'][0];
var email = e.namedValues['Email'][0];
var date = e.namedValues['Date'][0];
logSheet.appendRow([name,email,date,newDocID]);
//Trigger
ScriptApp.newTrigger("sendEmail").timeBased().after(15000).create();
//sendEmail();
}
function sendEmail() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var logSheet = sheet.getSheetByName("Log");
var logSheetData = logSheet.getDataRange().getDisplayValues();
var templateName = sheet.getSheetByName("Template Name").getRange(1, 1).getValue();
for (i = 1; i < logSheetData.length; i++) {
if (logSheetData[i][4] == "") {
//SEND EMAIL
var name = logSheetData[i][0];
var email = logSheetData[i][1];
var date = logSheetData[i][2];
var id = logSheetData[i][3];
var pdfName = templateName + "-" + name + "-" + date;
//PDF EMAIL
try{
var doc = DriveApp.getFileById(id);
var blob = doc.getBlob().getAs('application/pdf').setName(pdfName + ".pdf");
var subject = 'Document Created';
//GmailApp.sendEmail(email, subject, "This is just a test", {attachments: [blob]});
MailApp.sendEmail(email, subject, "", {attachments: [blob], name: pdfName});
}catch(err){
continue;
}
//Log Sheet Update
logSheet.getRange(i + 1, 5).setValue("Sent");
}
}
}
function onOpen() {
SpreadsheetApp.getUi().createMenu("Custom Menu")
.addItem("Build Form Submit Trigger", "formSubmitTrigger")
.addSeparator()
.addItem("Send Email", "sendEmail")
.addSeparator()
.addItem("Mismatch Check", "mismatchCheck")
.addToUi();
}
function formSubmitTrigger() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
ScriptApp.newTrigger("onFormSubmit").forSpreadsheet(sheet).onFormSubmit().create();
}
function mismatchCheck() {
var result = "";
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var templateLink = sheet.getSheetByName("Template Link").getRange(1, 1).getValue();
var formResponsesSheet = sheet.getSheetByName("Form Responses 1");
var formResponsesHeader = formResponsesSheet.getRange(1, 2, 1, formResponsesSheet.getLastColumn() -1).getValues();
var docBody = DocumentApp.openByUrl(templateLink).getBody().getText();
var matches = docBody.match(/<</g); var noOfLessThanMatches = matches.length;
var matches = docBody.match(/>>/g); var noOfMoreThanMatches = matches.length;
var lessThan = docBody.search(/<</g);
var moreThan = docBody.search(/>>/g);
Logger.log([noOfLessThanMatches,noOfMoreThanMatches]);
result += "<b>Less Than Signs:</b> " + noOfLessThanMatches + "<br>";
result += "<b>More Than Signs:</b> " + noOfMoreThanMatches + "<br>";
result += "<br><b>Doc to Form Check</b><br>";
var newDocBody = docBody;
var reverseArray = [];
for (i = 0; i < noOfLessThanMatches; i++) {
var lessThan = newDocBody.search(/<</g);
var moreThan = newDocBody.search(/>>/g);
var subString = newDocBody.substring(lessThan + 2,moreThan);
Logger.log(subString);
var indexOf = formResponsesHeader[0].indexOf(subString);
if (indexOf > -1) {
result += subString + " - FOUND<br>";
} else {
result += subString + " - NOT FOUND<br>";
}
reverseArray.push(subString);
newDocBody = newDocBody.replace("<<" + subString + ">>","XX")
}
result += "<br><b>Form to Doc Check</b><br>";
for (z = 0; z < formResponsesHeader[0].length; z++) {
var thisString = formResponsesHeader[0][z];
var indexOf = reverseArray.indexOf(thisString);
if (indexOf > -1) {
result += thisString + " - FOUND<br>";
} else {
result += thisString + " - NOT FOUND<br>";
}
}
Logger.log(result);
var htmlOutput = HtmlService
.createHtmlOutput('<p>' + result + '</p>')
.setWidth(400)
.setHeight(500);
SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'RESULT');
}
UPDATE: I have pasted the whole code instead above so you guys can see
You have to register onFormSubmit as the function that handles the form submit trigger. Have you registered the function "onFormSubmit" like this:
ScriptApp.newTrigger('onFormSubmit').forForm(form).onFormSubmit().create();
You might also want to check the registered triggers by clicking on Edit > Current project's trigger from your Apps Script project.
[Edit] Since the trigger is created properly, change the first the line of the trigger code from:
function onFormSubmit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
to this:
function onFormSubmit(e) {
var sheet = SpreadsheetApp.openById(e.source.getDestinationId());

Send Email - Keep Cell Formatting

I have a google spreadsheet that sends student information contained in a column that is queried and concatenated from another sheet. The queried information is separated by carriage returns. This column is then emailed to families triggered by a formula that calculates how many carriage returns should be in the cell.
That part I have taken care of in the sheet itself. I need assistance with emailing the column and maintaining the format of the cell. I've been able to do that with the code I have below, but it sends ALL of the data in column D in every email. I need it to only send what's located in the appropriate row for the email.
The main portion of the code that's giving me trouble, I think, is the following:
var OriginalString = SpreadsheetApp.getActive().getRange("D2:D").getValues();
var NewString = OriginalString.toString().replace(/\n/g, '<br>');
Any help would be appreciated!
function SendEmail3() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet3');
var startrow = 2;
var lastRow = ss.getLastRow();
var lastCol = 10;
var range = ss.getRange(2, 1, lastRow, lastCol);
var data = range.getValues();
for (var i = 0; i < data.length; i++) {
var row = data[i];
var AccountName = row[0];
var email = row[1];
var Parent = row[2];
var Consent = row[4];
var StudentData = row[3];
var CarriageReturns = row[6];
var Trigger = row[7];
var emailSent = row[8];
var subject = "Your Application";
var OriginalString = SpreadsheetApp.getActive().getRange("D2:D").getValues();
var NewString = OriginalString.toString().replace(/\n/g, '<br>');
var message = "<HTML><BODY><font size=4>" +
"<P>" + "Hello " + Parent + ','
+"<BR>
+"<BR>" + NewString + "<BR>"
+"</HTML></BODY>";
var recipientsTo = email;
if (AccountName.length > 0 && Trigger >= CarriageReturns && emailSent != 'EMAIL_SENT') {
MailApp.sendEmail({
subject: subject,
to: recipientsTo,
htmlBody: message
});
ss.getRange(startrow + i, 9).setValue('EMAIL_SENT');
}
}
}
Is this what your looking for?
I set it up so that you can see the message on a modeless dialog rather than sending emails.
function SendEmail3() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet3');
var startrow = 2;
var lastRow = ss.getLastRow();
var lastCol = 10;
var range = ss.getRange(2, 1, lastRow, lastCol);
var data = range.getValues();
var html='';//Remove
for (var i = 0; i < data.length; i++) {
var row = data[i];
var AccountName = row[0];
var email = row[1];
var Parent = row[2];
var Consent = row[4];
var StudentData = row[3];
var CarriageReturns = row[6];
var Trigger = row[7];
var emailSent = row[8];
var subject = "Your Application";
var NewString = StudentData.split('\n').join('<br />');
//var message = "<HTML><BODY><font size=4>" + "<P>" + "Hello " + Parent + ',' + "<BR>" +"<BR>" + NewString + "<BR>" +"</HTML></BODY>";
var message=Utilities.formatString('<HTML><BODY><font size=4><P>Hello %s,<BR><BR>%s<BR></HTML></BODY>', Parent,NewString);
var recipientsTo = email;
if (AccountName.length > 0 && Trigger >= CarriageReturns && emailSent != 'EMAIL_SENT') {
//MailApp.sendEmail({subject: subject,to: recipientsTo,htmlBody: message});
html+=Utilities.formatString('%s- %s',i+1,message);//Remove
//ss.getRange(startrow + i, 9).setValue('EMAIL_SENT');
}
}
var userInterface=HtmlService.createHtmlOutput(html);//Remove
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Email Message');//Remove
}
Utilities.formatString()

How to fix the issue mail merge issue

I am trying to create an approval flow using sheet mail merge with approval buttons in the mail . Mail could generate when the user submits the HTML form.
Below script is not working I have attached the script with sample sheet.
I am not able to identify the exact issue, please help me to fix or identify
Sample Sheet
var REQUESTS_STATE_COLUMN = 32;
var STATE_APPROVERS_EMAILED = "EMAILED_Response Pending";
var STATE_APPROVED = "Approved";
var STATE_DENIED = "Rejected";
function sendEmail(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var dataRange = sheet.getRange("A2:AH2");
var data = dataRange.getValues();
for (i in data) {
var rowData = data[i];
var email = e.namedValues["Email Address"];
var emailAddress = rowData[30];
var submiterEmail = rowData[1];
var ProjectName = rowData[2];
var SrDesign = "Sr. Design Architect Services";
var PerHourRate = rowData[6];
var NumberOfHours = rowData[7];
var TotalRate = rowData[8];
var Contact = "Contact Centre Expert";
var PerHourRate2 = rowData[10];
var NumberOfHours2 = rowData[11];
var NTotalRate2 = rowData[12];
var NJrDesign = "Jr. Design Architect";
var PerHourRate3 = rowData[14];
var NumberOfHours3 = rowData[15];
var TotalRate3 = rowData[16];
var Outsourced = "Outsourced Technical Support Resource";
var PerHourRate4 = rowData[18];
var NumberOfHours4 = rowData[19];
var TotalRate4 = rowData[20];
var Supplier = "Supplier Management";
var PerHourRate5 = rowData[22];
var NumberOfHours5 = rowData[23];
var TotalRate5 = rowData[24];
var Project = "Project Management & Execution";
var PerHourRate6 = rowData[26];
var NumberOfHours6 = rowData[27];
var TotalRate6 = rowData[28];
var UserAccount = rowData[28];
var GrandTotalRate = rowData[29];
var seq = e.values[1];
var url = ScriptApp.getService().getUrl();
var sheet = SpreadsheetApp.openById('1i5x0oqpCDgOZO2Nbly4SpNkWpLbTXJhT6pPOfQ7NuEc').getSheetByName("Sheet1");
var cellval = range.getCell(row,1).getValue();
var options = '?approval=%APPROVE%&reply=%EMAIL%'
.replace("%EMAIL%",e.namedValues["User Email Address"])
var approve = url+options.replace("%APPROVE%","Approved")+'&row='+data+'&cellval='+cellval;
var reject = url+options.replace("%APPROVE%","Rejected")+'&row='+data+'&cellval='+cellval;
var subject = 'Technology Charges for '+ProjectName+'';
var html = '<p style="font-family:Verdana; fontsize=9px">Hello Recipient,<br/><br/><br/><br/>Referance No: '+cellval+'<br/><a href='+ approve +'> <b>approve </b></a><a href='+ reject +'> <b>Reject</b></a><br/>'
MailApp.sendEmail({
to: emailAddress,
subject: subject,
htmlBody: html,
});
//Add a state in the form spreadsheet with APPROVERS_EMAILED state
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
sheet.getRange(lastRow, REQUESTS_STATE_COLUMN+1).setValue(STATE_APPROVERS_EMAILED);
}
}
function doGet(e){
var answer = (e.parameter.approval === 'Approved') ? 'Yes -Approved!' : 'No-Rejected ';
var cellval = e.parameter.cellval;
var email = e.parameter.reply;
var sheet = SpreadsheetApp.openById("1i5x0oqpCDgOZO2Nbly4SpNkWpLbTXJhT6pPOfQ7NuEc").getSheetByName("Sheet1");
var data = sheet.getDataRange().getValues();
var headers = data[0];
var approvalCol = headers.indexOf("Approval") + 1;
if (0 === approvalCol) throw new Error ("Must add Approval column.");
// Record approval or rejection in spreadsheet
var row = ArrayLib.indexOf(data, 0, cellval);
if (row < 0) throw new Error ("Request not available."); // Throw error if request was not found
sheet.getRange(row+1, approvalCol).setValue(e.parameter.approval);
// Display response to approver
var app = UiApp.createApplication();
app.add(app.createHTML('<h2>Thank you..! Your response has been recorded'+' saying: '+ answer + '</h2>'))
return app
}
The getCell requires integer value for row and column but instead you are passing the entire row (rowData). You need to replace the line 45 to the below line.
var cellval = dataRange.getCell(i+1, 1).getValue()

Delete a newly created document?

I am using a script to process a form as it is submitted. Part of it involves merging data from the form with a google doc and then emailing that doc as a pdf. Is there anyway to delete the doc once it has been sent?
If it helps, here is my script:
function onFormSubmit(e) {
//Get Form Values
var candID = parseInt(e.values[1]);
var emailAddress = e.values[2];
//Get Additional Settings
var ssMaster = SpreadsheetApp.openById("0AierVcXWELCudDY2Y3J2Z1hoX3pLOXYzTW1pOVF3Wmc");
var settings_sheet = ssMaster.getSheetByName("Settings");
var candCodeLength = settings_sheet.getRange("B20").getValue();
var candCodeChars = settings_sheet.getRange("B21").getValue();
var tempDocumentID = settings_sheet.getRange("B14").getValue();
var candInfoSheet = ssMaster.getSheetByName("Candidate Information");
var candInfoLastRow = candInfoSheet.getLastRow();
var candInfoArray = candInfoSheet.getRange(2,1,candInfoLastRow,7).getValues();
//Find Corresponding Row for Form Entry
for(var i=0; i<candInfoArray.length; i++) {
if (candInfoArray[i][3] === candID) {
var row = i+2;
}
}
var candIDRowNumber = row;
//Create & Record Candidate Code
do {
var candCode = createCandCode(candCodeLength, candCodeChars);
}
while(checkCandCode(candInfoArray, candCode) === true);
candInfoSheet.getRange(row,6,1,1).setValue(candCode);
candInfoSheet.getRange(row,7,1,1).setValue(emailAddress);
//Create PDF
var docid = DocsList.getFileById(tempDocumentID).makeCopy("Character Reference Instructions").getId();
var doc = DocumentApp.openById(docid);
Logger.log(candInfoArray);
Logger.log(row);
var firstName = candInfoArray[(row-2)][1];
var lastName = candInfoArray[(row-2)][0];
var body = doc.getActiveSection();
body.replaceText("<<first>>", firstName);
body.replaceText("<<last>>", lastName);
body.replaceText("<<code>>", candCode);
doc.saveAndClose();
//Send Email
var message = "You have successfully completed the NHS Registration form.\n\n Your Candidate Code (different from your Candidate ID) is \"" + candCode + "\" and should be given to your character reference so that they can fill out your character reference form.\n\n If you have any questions, please email Ann Perham at ann_perham#needham.k12.ma.us." ;
var subject = "NHS Registration Confirmation & Character Reference Instructions";
var advancedArgs = {name: "Ann Perham", replyTo: "ann_perham#needham.k12.ma.us", attachments: doc.getAs("application/pdf")};
MailApp.sendEmail(emailAddress, subject, message, advancedArgs);
}
You can use doc.setTrashed right at the end of your function while it is still the active document.