Google Form Document Automation - google-apps-script

I have been receiving 2 main issues back upon a google form submission- the first being that the e.values I have set up cannot be read and the second that the Doclist is not defined. I have already set the triggers for the e.values and tried using e.namedvalues as well. I would like to eliminate the second issue by sending a doc and not a pdf to the form submitter, however it is most important that I get the first issue addressed first.
I am using framework that I have modified to fit my own documents, so that may be where I am encountering issues.
// G. Hopper
// Subcontract Generator
// Get template from Google00 Docs and name it
var docTemplate = "16bdl2myh7f0ywlxmf3iimq4Nz6-j8VTs7hkMbshRjp0";
var docName = "Subcontract";
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var sub_name = e.namedValues["Subcontractor Name"].toString();
var sub_address = e.namedValues["Subcontractor address"].toString();
var proj_name = e.namedValues["Project Name"].toString();
var own_name = e.namedValues["Owner Name"].toString();
var own_address = e.namedValues["Owner Address"].toString();
var designer = e.namedValues["Design Firm"].toString();
var design_address = e.namedValues["Design Firm Address"].toString();
var proj_address = e.namedValues["Project Address"].toString();
var scope = e.namedValues["Scope of work"].toString();
var date_bid = e.namedValues["Date on bid"].toString();
var sub_value = e.namedValues["Subcontract Value"].toString();
var date_pay = e.namedValues["Date of the month pay applications are due"].toString();
var email = e.namedValues["Your email address"].toString();
var day = e.namedValues["Day"].toString();
var month_year = e.namedValues["Month and Year"].toString();
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy('Subcontract for '+sub_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('keySubName', sub_name);
copyBody.replaceText('keySubAddress', sub_address);
copyBody.replaceText('keyProject', proj_name);
copyBody.replaceText('keyOwner', own_name);
copyBody.replaceText('keyOwnAddress', own_address);
copyBody.replaceText('keyDesigner',designer);
copyBody.replaceText('keyDesignAddress', design_address);
copyBody.replaceText('keyProjAdd', proj_address);
copyBody.replaceText('keyScope', scope);
copyBody.replaceText('keyBidDate', date_bid);
copyBody.replaceText('KeySubValue', sub_value);
copyBody.replaceText('keyPayApp', date_pay);
copyBody.replaceText('keyDay', day);
copyBody.replaceText('keyMonthDay', month_year);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = 'Subcontract'
var body = "Here is your subcontract for " + sub_name + "";
MailApp.sendEmail(email, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DocsList.getFileById(copyId).setTrashed(true);
}

Related

App Script to insert an image from google drive to a google doc

Have collected info through a google form to a google sheet. Part of that info is the path to an image stored on drive. I have an app script that replaces key words on a document with the data collected in the sheet. I can get it to replace a piece of text, {{image}} for example with the url stored but I cannot get it to actually put a copy of the image into the document.
Any suggestions.
Code below
// #ts-nocheck
function autoFillGoogleDocFromForm(e) {
//e.values is an array of form values
var timestamp = e.values[0];
var email = e.values[1];
var who = e.values[2];
var employeeorcon = e.values[3];
var location = e.values[4];
var roomorarea = e.values[5];
var type = e.values[6];
var dateofworks = e.values[7];
var imageofcompletedcon = e.values[8];
var checkedoffintext = e.values[9];
var checkname = e.values[10];
var checkco = e.values[11];
var checkeddate = e.values[12];
//file is the template file, and you get it by ID
var file = DriveApp.getFileById("1WcYKvsRFbKK73J-ep66mR9drZyrkWap-x30rO-kVUcM");
//We can make a copy of the template, name it, and optionally tell it what folder to live in
//file.makeCopy will return a Google Drive file object
var folder = DriveApp.getFolderById("1MeU3-N3BMqOPvoaSGr2XassibR2XajdN")
var copy = file.makeCopy(roomorarea + '_' + timestamp, folder);
//Once we've got the new file created, we need to open it as a document by using its ID
var doc = DocumentApp.openById(copy.getId());
//Since everything we need to change is in the body, we need to get that
var body = doc.getBody();
//Then we call all of our replaceText methods
body.replaceText('{{location}}', location);
body.replaceText('{{room}}', roomorarea);
body.replaceText('{{completedby}}', who);
body.replaceText('{{checkedby}}', checkname);
body.replaceText('{{checkeddate}}', checkeddate);
body.replaceText('{{insdate}}', dateofworks);
body.replaceText('{{Empcon}}', employeeorcon);
body.replaceText('{{Type}}', type);
body.replaceText('{{image}}', imageofcompletedcon);
body.replaceText('{{methchk}}', checkedoffintext);
body.replaceText('{{checker}}', checkname);
body.replaceText('{{cocheck}}', checkco);
body.replaceText('{{datecheck}}', checkeddate);
//Lastly we save and close the document to persist our changes
doc.saveAndClose();
}
New to this, but tried insertimage etc, but really a bit beyond me.

Short Script for Converting Google Forms Data to PDF not sending email

I am working with this tutorial to try to convert data submited from a google form to a PDF. Problem is, I am not getting any emails. The spreadsheet updates fine, but no emails.
I am prety comfortable with the coding but I never have used Google Drive scripting. It seems some of the code may be outdated. I changed "DocsList" to "DriveApp" via find and replace and I changed "MailApp" to gmail app.
I am not sure where to go from here or even how to use the debugger when waiting for a formsubmit event. Any advice would be greatly apreciated. Thanks.
Here is my code:
//:שְׁמַע יִשְׂרָאֵל יהוה אֱלֹהֵינוּ יהוה אֶחָד
//Christian Shields (ChristianShields#gmail.com)
//Job Application Google Form to PDF converter
//11/2/15
//get the document from Google Docs and name it
var docTemplate = "1wgkvO-1xrVGJkD-JJ2FMRbQj_bfGu7qFAa6pTEJ61Cw";
var docName = "NewCherryHillJobApplication";
function onFormSubmit(e){
//set the email address where the finished document will go.
var docs_email = "ChristianShields#gmail.com";
//get information from the newly submited form
var full_name = e.values[2];
var age = e.values[3];
var address = e.values[4];
var phone = e.values[5];
var alt_phone = e.values[6];
var email
//Get the document template and copy it as a new temp document. Save the document ID's
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+' for '+full_name)
.getId();
//open the temp document
var copyDoc = DocumentApp.openById(copyId);
//go to the temp documents body
var copyBody = copyDoc.getActiveSection();
//replace the text in the temp document
copyBody.replaceText('keyFullName', full_name);
copyBody.replaceText('keyAge', age);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyPhone', phone);
copyBody.replaceText('keyAltPhone', alt_phone);
copyBody.replaceText('keyEmail', email);
//save and close the temp document
copyDoc.saveAndClose();
//convert the temp document to pdf
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
//Attach PDF and send the email
var subject = "New Doc's Job Application Submited Online";
var body = "A new job application has been recieved from " + full_name + ". Primary phone number for this applicant is: " + phone + "";
GmailApp.sendEmail(docs_email, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DriveApp.getFileById(copyId).setTrashed(true);
} //End of dunction "onFormSubmit
This line of code:
var copyBody = copyDoc.getActiveSection();
Uses a method named getActiveSection(). That method is not in the documentation, and it doesn't appear in the auto-complete list. It doesn't exist. Strangely enough, it doesn't produce an error. I can't find it in any deprecated list.
I just ran your code, and it sent me an email with a pdf file. I commented out some parts.
function onFormSubmit(e){
//set the email address where the finished document will go.
var docs_email = "your_email#gmail.com";
//get information from the newly submited form
var full_name = 'First Last';
var age = '99';
var address = '77 Maple Grove';
var phone = '800 Call Joe';
var alt_phone = 'none';
var email
//Get the document template and copy it as a new temp document. Save the document ID's
var copyId = DriveApp.getFileById('Your Document ID Here')
.makeCopy('Novem3'+' for '+full_name)
.getId();
//open the temp document
var copyDoc = DocumentApp.openById(copyId);
//go to the temp documents body
copyDoc.getBody()
var copyBody = copyDoc.getActiveSection();
//replace the text in the temp document
/* copyBody.replaceText('keyFullName', full_name);
copyBody.replaceText('keyAge', age);
copyBody.replaceText('keyAddress', address);
copyBody.replaceText('keyPhone', phone);
copyBody.replaceText('keyAltPhone', alt_phone);
copyBody.replaceText('keyEmail', email);
*/
//save and close the temp document
copyDoc.saveAndClose();
//convert the temp document to pdf
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
//Attach PDF and send the email
var subject = "New Doc's Job Application Submited Online";
var body = "A new job application has been recieved from " + full_name + ". Primary phone number for this applicant is: " + phone + "";
GmailApp.sendEmail(docs_email, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
//DriveApp.getFileById(copyId).setTrashed(true);
} //End of dunction "onFormSubmit
I've found that if you are sending the emails to yourself they may not turn up in your inbox, so take a look at "Sent Mail" to see if they are there.

Broken Submission Form

I have a survey form that we use for our clients. It is a series of multiple choices questions, and a few text field entries. At the end, you click "submit" and an email is sent containing all the responses to our Quality Manager. Recently, the form stopped working, and I found many people who successfully fixed the issue by changing docslist to DriveApp. However, now I am getting the error:
TypeError: Cannot read property "response" from undefined. (line 10, file "")
The entire code reads as follows:
/// Get template from Google Docs and name it
var docTemplate = "1vCv-NR9c2G5q6f6EJ2CL4zAEQe_37OE7MgsSLTIKheY"; // *** replace with your template ID ***
var docName = "ClientSurvey";
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
Logger.log(Utilities.jsonStringify(e));
var formResponses = e.response.getItemResponses();
Logger.log(formResponses[0].toString());
var service_type = formResponses[0].getResponse().toString();
var email_address = "notrealaddress#ntainc.com, notrealaddress#ntainc.com"
//var service_type = e.values[0];
var d = new Date();
var timeStamp = d.getTime();
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+timeStamp)
.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('keyServiceType', service_type);
for (var i = 0; i < formResponses.length; i++) {
copyBody.appendParagraph(formResponses[i].getItem().getTitle().toString());
copyBody.appendParagraph(formResponses[i].getResponse().toString());
copyBody.appendParagraph(" ");
}
// 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 = "Customer Survey";
var body = "Here is a New Customer Survey";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DriveApp.getFileById(copyId).setTrashed(true);
}
Please help!
This is more of a comment than an answer, but I dont have enough rep to comment yet.
Check your trigger, there is two types of FormSubmit triggers, one for sheets and one for forms, if you are using the wrong one that could be what is causing your issues.

Moving a created file from template to folder with google script

I need help with a google script that I have written which takes the responses from a google form and transfers the responses from the response spreadsheet into a google doc template. The script that I have written now has the proper trigger needed to create the google doc that I want to create but I do not know what needs to be added to have the new document save in a folder that is a created folder in my drive NOT just the my drive folder. Any help would be appreciated. Below is the script I already have written.
// Get template from Google Docs and name it
var docTemplate = "1NPiAbaB2wciyJUhJE4AvxZ1dCB_Uu5kf24eSxLC_BfI";
var docName = "AttrVaRepairTemp";
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var timestamp = e.values[0];
var contact_name = e.values[1];
var company_name = e.values[2];
var phone_number = e.values[3];
var email_address = e.values[4];
var contact_address = e.values[5];
var item_type = e.values[6];
var manufacturer = e.values[7];
var model_number = e.values[8];
var serial_number = e.values[9];
var description = e.values[10];
var symptoms = e.values[11];
var accepted_by = e.values[12];
var warranty = e.values[13];
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy('Repair Form- '+contact_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('keytimestamp', timestamp);
copyBody.replaceText('keyacceptedby', accepted_by);
copyBody.replaceText('keycontactname', contact_name);
copyBody.replaceText('keycompanyname', company_name);
copyBody.replaceText('keycontactphone', phone_number);
copyBody.replaceText('keycontactemail', email_address);
copyBody.replaceText('keycontactaddress', contact_address);
copyBody.replaceText('keymanufacturer', manufacturer);
copyBody.replaceText('keymodel', model_number);
copyBody.replaceText('keyserial', serial_number);
copyBody.replaceText('keyitemtype', item_type);
copyBody.replaceText('keywarranty', warranty);
copyBody.replaceText('keydescription', description);
copyBody.replaceText('keysymptoms', symptoms);
// Save and close the temporary document
copyDoc.saveAndClose();
(Copied Serge Insas answer from a similar question elsewhere)
See this old post : (https://stackoverflow.com/questions/13532114/google-apps-script-addtofolder-adds-to-folder-and-mydrive/13536275#13536275)
code is as follows :
function moveFromRoot(){
folder=DocsList.createFolder("MyFolder");
var file=DocsList.createFile('File2', 'Empty');
file.addToFolder(folder);
file.removeFromFolder(DocsList.getRootFolder());
}
but as mentioned in the answer, you can create the file using the folder object itself (folder.createFile('blabla'))

How do I create a form letter where some text is not printed if a field on a Google form is left blank

My company recently switched to Google Apps and I am trying to covert Word and Excel docs to Google Docs. I am completely new to Google App Script and am stuck. I have been searching for a few days a have not found what I am looking for.
I have a Google form that is emailed to a sales person. After it is completed the Google spreadsheet is updated and then sends a form letter to the sales person summarizing their input. Some of the fields on the form are optional. How do I create a template that does not include some of the form letter text if the question was left unanswered?
For example, one of the optional fields is for a customer website address, if the customer does not have a website I don’t want the words website to show up on the form.
If anyone has any “For Dummies” instructions on how to do this I would really appreciate it.
Thanks.
Here is what I have so far:
// Business Review Report
// Get template from Google Docs and name it
var docTemplate = "1gRk2irahyW2Sf4pQMTDykXlMQqYgbe1Ba1vkh20KDYo";
var docName = "Business Review";
// When Form Gets submitted
function onFormSubmit (e) {
//Get information from form and set as variables
var variablename = "static entry or form value"
var email_address = e.values[1];
var Business_Name = e.values[2];
var Business_Address = e.values[3];
var Phone_Number = e.values[4]
var Email_address = e.values[5];
var Website = e.values[6];
var Participants = e.values[7];
var Agenda = e.values[8];
var Updates_and_Progress1 = e.values[9];
var Updates_and_Progress2 = e.values[10];
var Updates_and_Progress3 = e.values[11];
var Current_Issues1 = e.values[12];
var Current_Issues2 = e.values[13];
var Current_Issues3 = e.values[14];
var Next_Steps = e.values[15];
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+ Business_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('keyBusinessName', Business_Name);
copyBody.replaceText('keyBusinessAddress', Business_Address);
copyBody.replaceText('keyPhoneNumber', Phone_Number);
copyBody.replaceText('keyEmailaddress', email_address);
copyBody.replaceText('keywebsite', Website);
copyBody.replaceText('keyParticipants', Participants);
copyBody.replaceText('keyAgenda', Agenda);
copyBody.replaceText('keyUpdatesAndProjects1', Updates_and_Progress1);
copyBody.replaceText('keyUpdatesAndProjects2', Updates_and_Progress2);
copyBody.replaceText('keyUpdatesAndProjects3', Updates_and_Progress3);
copyBody.replaceText('keyCurrentIssues1',Current_Issues1);
copyBody.replaceText('keyCurrentIssues2', Current_Issues2);
copyBody.replaceText('keyCurrentIssues3', Current_Issues3);
copyBody.replaceText('keyNextSteps', Next_Steps);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
// Attach PDF and send the email
var subject = "Business Review";
var body = "Business Review for " + Business_Name + "";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
// Delete temp file
DocsList.getFileById(copyId).setTrashed(true);
}
It works, but the resulting PDF also includes text for the unfilled fields like CurrentIssues2.
I am not sure if I am explaining this clearly so please respond with any questions and I will try to be more clear.
Thanks again,
Lisa
Your form questions apparently have default values that you don't want in your form letter. You can check for those defaults and replace them with something more suitable, such as a blank string.
...
// If website question was not answered, leave blank
var Website = e.values[6];
if (Website == 'website') Website = '';
...
This alternative uses the Ternary or Conditional Operation, and is more compact:
...
// If website question was not answered, leave blank
var Website = (e.values[6] == 'website') ? '' : e.values[6];
...