Google Form to Document Merge to Pdf to Mail - google-apps-script

I think my issue is in the e.values I am using along with the ('keyXXXXX', XXXXX); that I am using.
The original code I used was something I borrowed from TJ Houston's site. I am using it for an application process. I wrote the code following the process of using
var last_name = e.values [1]
and matching it with the
copyBody.replaceText('keyLastName', last_name);
It worked for most of the entries but failed on
var emergency_phone = e.values[23];
matched with
copyBody.replaceText('keyEmergencyContactPhone', emergency_phone);
On that form and code I had over 100 lines of Var and CopyBody matches. I created a simpler one to test, which fails as soon as you get to cphone.
// LAC Employement Applicaiton Script based on TJ Houston tjhouston.com (tj#tjhouston.com)
// LAC Employment Application
// Get template from Google Docs and name it
var docTemplate = "1Vb0P03a6qPfJOvo_bP_3zUM159XP18c3tfBL62L_mIs"; // *** replace with your template ID ***
var docName = "Applicaiton Review";
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var email_address = "jreach#gmail.com";
var last_name = e.values[1];
var first_name = e.values[2];
var middle_name = e.values[3];
var current_address = e.values[4];
var ccity = e.values[5];
var cstate = e.values[6];
var czip = e.values[7];
var years = e.values[8];
var home_phone = e.values[9];
var cphone = e.values[10];
var email = e.values[11];
var emergency_contact = e.values[12];
var ephone = e.values[13];
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+' for '+last_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('key1', last_name);
copyBody.replaceText('key2', first_name);
copyBody.replaceText('key3', middle_name);
copyBody.replaceText('key4', current_address);
copyBody.replaceText('key5', ccity);
copyBody.replaceText('key6', cstate);
copyBody.replaceText('key7', czip);
copyBody.replaceText('key8', years);
copyBody.replaceText('key8', home_phone);
copyBody.replaceText('key9', cphone);
copyBody.replaceText('key10', email);
copyBody.replaceText('key11', emergency_contact);
copyBody.replaceText('key12', ephone);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "Applicaiton Review";
var body = "You have received an application from " + last_name + "";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DriveApp.getFileById(copyId).setTrashed(true);
}

when replacing multiple keys in a document you are quite right that the keys must be unique. Personally I bracket all keys with # symbols which works for me e.g. #key1# won't be confused with #key10#

Related

Modifying a Google doc template and then sending it as a docx in an email whenever a google form is filled in

I'm trying to modify a template document with pertinent information from a google form submission and then send an email with the filled in document as a word doc to the person who filled the form in. I can manage to update the template and I can even get as far as attaching it as a pdf, but it needs to be editable by the receiver so that isn't really an option. Here is my code:
//Set template variables
var docTemplate = "1_l4T-MVXYXWPvirgE9aE25hKOejTqf9AcfHCKRC67Fk";
var docName = "Editorial Briefing Form";
//Get pertinent info from form
function onFormSubmit(e) {
var timeStamp = e.values[1];
var RequestorName = e.values[2];
var Account = e.values[3];
var JobNumber = e.values[4];
var Files = e.values[6];
var StartDate = e.values[7];
var BudgetHours = e.values[8];
var ActualDeadline = e.values[10];
var Email = e.values[11];
// Get template and save a copy with a new name
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+' for '+RequestorName)
.getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
//replace tags with form info
copyBody.replaceText('keyAccount', Account);
copyBody.replaceText('keyJobNumber', JobNumber);
copyBody.replaceText('keyStartDate', StartDate);
copyBody.replaceText('keyRequestorName', RequestorName);
copyBody.replaceText('KeyFiles', Files);
copyBody.replaceText('KeyBudgetHours',BudgetHours);
copyBody.replaceText('KeyActualDeadline', ActualDeadline);
copyDoc.saveAndClose()
MailApp.sendEmail(Email, 'test', 'see attachment', {attachments:[copyDoc]});
}
The only thing I've seen online involves Google OAuth, but I have no idea about that.
Any help would be hugely appreciated.
Thanks
Tom
I just figured out something similar. I couldn't get it to work from onFormSubmit(e), but I set it to run as a trigger from spreadsheet on form submit, and then told it to grab the last row of data, because forms submit puts that data in the last row (unless you have another script sorting things). So, my code looked like this:
function FormSubmitEmail(){
var templateid = "your template id here";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var row = sheet.getLastRow();
var data = sheet.getRange(5,1,sheet.getLastRow()-1,sheet.getLastColumn()).getValues();
var today = Utilities.formatDate(new Date(), "CST", "MM/dd/yy");
var firstname = sheet.getRange("B"+row).getValues();
var lastname = sheet.getRange("C"+row).getValues();
var docname = (lastname+", "+firstname+" "+today);
var folder = DriveApp.getFolderById("I have mine saving a copy also to a folder, your folder ID here");
var docid = DriveApp.getFileById(templateid).makeCopy(docname, folder).getId();
Logger.log(docid);
var doc = DocumentApp.openById(docid);
var body = doc.getActiveSection();
body.replaceText("%DateCreated%",(sheet.getRange("A"+row).getValues()));
body.replaceText("%FirstName%",(sheet.getRange("B"+row).getValues()));
body.replaceText("%LastName%",(sheet.getRange("C"+row).getValues()));
body.replaceText("%EmailAddress%",(sheet.getRange("M"+row).getValues())); //etc.
doc.saveAndClose();
var message = "See attached, or find in folder: https://drive.google.com/drive/folders/[your folder id here]"; // Customize message
var emailTo = "email2#gmail.com, email1#gmail.com" // replace with your email
var subject = "A form has been submitted!."; // customize subject
var pdf = DriveApp.getFileById(docid).getAs('application/pdf').getBytes();
var attach = {fileName:'Autogenerated template.pdf',content:pdf, mimeType:'application/pdf'}; // customize file name: "Autogenerated template"
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});
}

copyDoc.saveAndClose(); Missing ) after argument list Google Sheet Script

I do not not know coding - I'm trying to run the script below and recieve the error Missing ) after argument list on line 79 copyDoc.saveAndClose();
Blockquote
Here is the url for the doc:
https://docs.google.com/document/d/1FcbVBHmCcDfjcaKXSU5UeaOD30h1d5yTyQp_s28VPzc/edit?usp=sharing
here is the script. Please advise. Sincere Thanks.
function myFunction() {
// rsaez#shsd.org
// Travel Request
// Get template from Google Docs and name it
var docTemplate = "1FcbVBHmCcDfjcaKXSU5UeaOD30h1d5yTyQp_s28VPzc";
// *** replace with your template ID ***
var docName = "Travel_Request";
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var email_address = "rsaez#shsd.org, rsaez#shsd.org";
var Building = e.values[5];
var Request = e.values[6];
var Total_Days = e.values[7];
var Substitute_Needed = e.values[8];
var Staff_Member_Type = e.values[9];
var Coverage_Type = e.values[10];
var Time_of_Day = e.values[11];
var Coverage = e.values[12];
var Request_Type = e.values[13];
var Destination = e.values[14];
var Purpose = e.values[15];
var City = e.values[16];
var State = e.values[17];
var Purpose_is_related_to = e.values[18];
var Registration = e.values[19];
var Lodging = e.values[20];
var Lodging_Cost = e.values[21];
var Lodging_Total = e.values[22];
var Meals = e.values[23];
var Meals_Cost = e.values[24];
var Meals_Total = e.values[25];
var Mileage = e.values[26];
var Other = e.values[27];
var Travel_Cost = e.values[28];
var Miscellanous = e.values[29];
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+full_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyDate',
copyBody.replaceText('keyName',
copyBody.replaceText('keyPosition',
copyBody.replaceText('keyBuilding',
copyBody.replaceText('keyRequest',
copyBody.replaceText('keyDayT',
copyBody.replaceText('keySubstitute',
copyBody.replaceText('keyStaff',
copyBody.replaceText('keyDay',
copyBody.replaceText('keyTime',
copyBody.replaceText('keyCoverage',
copyBody.replaceText('keyRequest',
copyBody.replaceText('keyDest',
copyBody.replaceText('keyPurpose',
copyBody.replaceText('keyCity',
copyBody.replaceText('keySt',
copyBody.replaceText('keyPurpRelated',
copyBody.replaceText('keyRT',
copyBody.replaceText('keyLND',
copyBody.replaceText('keyLCP',
copyBody.replaceText('keyLT',
copyBody.replaceText('keyMND',
copyBody.replaceText('keyMCP',
copyBody.replaceText('keyMT',
copyBody.replaceText('keyMLT',
copyBody.replaceText('keyOT',
copyBody.replaceText('keyTotalBOE',
copyBody.replaceText('keyMisc',
// Save and close the temporary document
copyDoc.saveAndClose();
// copyDoc.saveAndClose() (options.cand_email);
// Convert temporary document to PDF
var pdf = DocsList.getFileById(copyId).getAs("application/pdf"
}
Your last line,
var pdf = DocsList.getFileById(copyId).getAs("application/pdf"
seems to be missing a ')' at the end. Perhaps that is the Missing ) after argument list.
The saveAndClose() method is automatically invoked at the end of script execution, for each open Document. Maybe it'll help: DocsList is deprecated since 2013, see https://developers.google.com/apps-script/sunset. You should use DriveApp instead.
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+' for '+full_name)
.getId();
var pdf = DriveApp.getFileById(copyId).getAs('application/pdf');

Changed to DriveApp still have same issue TypeError: Cannot read property "values" from undefined. (line 8, file "Code")

Changed to DriveApp still have same challenges and error message
var docTemplate = "1nBZvKTMk5b82tiNvMqG3obmbY-lBIpodrIjvH-_sf7g";
var DocName = "SpringHillDisciplineReport";
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var email_address = "kroper#lexrich5.org, lweaver#lexrich5.org, eddavis#lexrich5.org";
var studentname = e.values[2];
var studentgrade = e.values[6];
var date = e.values[5];
var reportername = e.values[3];
var locationofincident = e.values[8];
var reasonforthereferral = e.values[9];
var presentactiontakenbyadministrator = e.values[13];
var infractioncode = e.values [10];
var additionalcomments = e.values[14];
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(DocName+' for '+ studentname)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyStudentName', studentname);
copyBody.replaceText('keyDate', date);
copyBody.replaceText('keyStudentGrade', studentgrade);
copyBody.replaceText('keyLocationofIncident', locationofincident);
copyBody.replaceText('keyReasonfortheReferral',reasonforthereferral);
copyBody.replaceText('keyPresentActionTakenbyAdministrator',presentactiontakenbyadministrator);
copyBody.replaceText('keyAdditionalComments', additionalcomments);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "Discipline Referral Report";
var body = "Here is the Discipline Referral Report for " + studentname + "";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DriveApp.getFileById(copyId).setTrashed(true);
}
The DocsList service, which was deprecated in 2014, has been sunset and no longer functions. Users relying on DocsList should switch to DriveApp.
The two places in your code where you use DocsList should be updated for use with DriveApp
You cannot run this code from the code editor as it requires a submission from a form to work properly. You are receiving the error message that the value was undefined because there was no form submitted. The real problem is with DocsList

Attempting to Translate a Google From into a PDF Document that Then emails and am having script errors

So I am attempting to take the information from a google form that translates to a google spreadsheet to a google document that then converts to PDF and emails to the initial sender on submit.
I have the code written and am having an issue after the creation of the new document that is ment to be sent. The code is not finding the document that needs to be filled.
Below is the code followed by the error I am receiving. It is on line 23.
var docTemplate = "1mlAPTZ_UH1I3bRfgqiOVDI7PKgDXV-tGMpXLIwFoPjQ";
var docName = "Downtime";
function onFormSubmit (e) {
var Email_Address = e.values[2];
var Character_and_Player_Name = e.values[1];
var Major_Events_for_your_Character_Last_Session = e.values[3];
var Feedback_and_Questions = e.values[4];
var Major_Downtime_Action_A = e.values[5];
var Major_Downtime_Action_B = e.values[6];
var Major_Downtime_Action_C = e.values[7];
var Minor_Action_A = e.values[8];
var Minor_Action_B = e.values[9];
var Minor_Action_C = e.values[10];
var Minor_Action_D = e.values[11];
var Minor_Action_E = e.values[12];
var Minor_Action_F = e.values[13];
var Pack_Downtime = e.values[14];
var XP_Spends = e.values[15];
var Renown = e.values[16];
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+Character_and_Player_Name)
.getId();
var copyDoc = DocumentApp.openByID(copyId);
var copyBody = copyDoc.getActiveSection();
copybody.replaceText('keyCharacterandPlayerName', Character_and_Player_Name);
copybody.replaceText('keyMajorEventsforyourCharacterLastSession', Major_Events_for_your_Character_Last_Session);
copybody.replaceText('keyFeedbackandQuestion', Feedback_and_Questions);
copybody.replaceText('keyMajorDowntimeActionA', Major_Downtime_Action_A);
copybody.replaceText('keyMajorDowntimeActionB', Major_Downtime_Action_B);
copybody.replaceText('keyMajorDowntimeActionC', Major_Downtime_Action_C);
copybody.replaceText('keyMinorActionA', Minor_Action_A);
copybody.replaceText('keyMinorActionB', Minor_Action_B);
copybody.replaceText('keyMinorActionC', Minor_Action_C);
copybody.replaceText('keyMinorActionD', Minor_Action_D);
copybody.replaceText('keyMinorActionE', Minor_Action_E);
copybody.replaceText('keyMinorActionF', Minor_Action_F);
copybody.replaceText('keyPackDowntim', Pack_Downtime);
copybody.replaceText('keyXPSpends', XP_Spends);
copybody.replaceText('keyRenown', Renown);
copyDoc.saveAndClose();
var pdf = DocsList.getFileByID(copyID) .getAs("application/pdf");
var subject = "Downtime Copy"
var body = "Here is a copy of your submitted Downtime for Rage Across the Dunes for " + Character_and_Player_Name;
MailApp.sendEmail(Email_Address, subject, body, {htmlBody: body, attachments: pdf});
DocsList.getFileById(copyID).setTrashed(true);
}
TypeError: Cannot find function openByID in object DocumentApp. (line 23, file "Code")
Any help would be great I am learning as I go so any help would be useful.
Change the capital "D" to a lower case "d".
ID to Id
DocumentApp.openByID(copyId)
Needs to be:
DocumentApp.openById(copyId)

Copy, rename and move a document

I am trying to create a Google Doc based on form data. I have done this with other forms that take the Doc and save them as PDFs. With this script, I have been able to create new docs and rename the file, but I need to move them to a different folder. The code I used for doing this with PDFs works (at the very bottom) without problems but I can't figure out what I am doing wrong. I have not had any luck searching for working solutions online either.
var TEMPLATE_ID = 'template id number';
var folder = DriveApp.getFolderById('folder ID number');
// When Form Gets submitted
function onFormSubmit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
sheet = ss.getSheetByName("Goal Tracking"),
activeSheet = SpreadsheetApp.getActiveSheet(),
copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy(),
copyId = copyFile.getId(),
copyDoc = DocumentApp.openById(copyId),
copyBody = copyDoc.getActiveSection(),
numberOfColumns = sheet.getLastColumn(),
activeRowIndex = sheet.getActiveRange().getRowIndex(),
activeRow = activeSheet.getRange(activeRowIndex, 1, 1, numberOfColumns).getValues(),
headerRow = activeSheet.getRange(1, 1, 1, numberOfColumns).getValues(),
columnIndex = 0,
fileName = "Goals " + activeRow[0][2] + ' ' + activeRow[0][3]+'_'+activeRow[0][5];
//Get information from form and set as variables.
var lastName = e.values[2];
var firstName = e.values[3];
var programCode = e.values[4];
var goal1 = e.values[6];
var goal2 = e.values[7];
var goal3 = e.values[8];
// Replace place holder keys,in our google doc template
copyBody.replaceText('%First Name%', firstName);
copyBody.replaceText('%Last Name%', lastName);
copyBody.replaceText('%Program Code%', programCode);
copyBody.replaceText('%Goal Statement 1%', goal1);
copyBody.replaceText('%Goal Statement 2%', goal2);
copyBody.replaceText('%Goal Statement 3%', goal3);
// Save and close the temporary document
copyDoc.saveAndClose();
copyDoc.setName(fileName);
(continuing on)
Here is where the problem is
folder.addFile(newFile);
}
I do get an error in the execution transcript but I don't understand why I am getting it: 'Cannot find method addFile(Document)." I also tried to use:
copyDoc.makeCopy(fileName, folder).getId;
to set a file name and folder location but it also failed.
For what its worth, here is what I have used to create a PDF that does work in this script.
copyDoc.saveAndClose();
var pdfFile = DriveApp.createFile(copyFile.getAs("application/pdf"));
var pdfFile2 = pdfFile.setName(fileName);
folder.addFile(pdfFile2);
copyFile.setTrashed(true);
Thanks :)
This code moves the folder, and rename the file.
function myFunction() {
var dstFolderId = "0B1ECfqTCcLE8c09YZUtqTkVwU3c";
var targetFileId = "0B1ECfqTCcLE8SS1PRnJ1cVgxVlk";
var targetFile = DriveApp.getFileById(targetFileId);
var newFileName = "HelloWorld.pdf";
// Remove current parent folders
var parentFolders = targetFile.getParents();
while(parentFolders.hasNext()) {
var parent = parentFolders.next();
parent.removeFile(targetFile);
}
// Add the target file into the new folder
var dstFolder = DriveApp.getFolderById(dstFolderId);
dstFolder.addFile(targetFile);
// Rename if you want.
targetFile.setName(newFileName);
}