Google Form - not filled fields - google-apps-script

I started to use a Google Form recently. I created:
The Google form with some questions,
Spreadsheet where the script would put the answers
An template that would be filled with the answers, converted to PDF and sent to the e-mail address.
Everything works perfectly IF all the Google Form fields had been filled.
If there is at least one field that was left empty - all the answers are put correctly to the spreadsheet but get totally misplaced in the template... (fragment of my code below)
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var email_address = "myemail#myemail";
var project_name = e.values[1];
var owner = e.values[2];
var team_members = e.values[5];
var project_initiator = e.values[6];
var stakeholders = e.values[7];
var deadline = e.values[3];
var related_projects = e.values[8];
var deliverables = e.values[4];
var project_summary = e.values[9];
var contribution = e.values[10];
// Replace place holder keys,in our google doc template
copyBody.replaceText('keyProjectName', project_name);
copyBody.replaceText('keyOwner', owner);
copyBody.replaceText('keyTeamMembers', team_members);
copyBody.replaceText('keyProjectInitiator', project_initiator);
copyBody.replaceText('keyStakeholders', stakeholders);
copyBody.replaceText('keyDeadline', deadline);
copyBody.replaceText('keyRelatedProjects', related_projects);
copyBody.replaceText('keyProjectSummary', project_summary);
copyBody.replaceText('keyContribution', contribution);
And a fragment of the template:
http://zapodaj.net/images/ce3895cc6614f.png
Thank you for any advises, answers..

The easiest way to fix this issue would be to make all of the questions from your form a required questions.
That way, the user will be unable to leave an answer blank and your template will auto-populate in the correct order.
Hope that helps

Related

Can you get Google Forms to keep the answer images in a generated response document?

I am trying to build a questionnaire form and we have a question that clients will answer by selecting an image. When the response is submitted, I have it set up to save the response in a Google Sheet, and then save a Google Doc with that information. I know we can see the images selected in individual responses, but since this will go out to every client who requests our services on a project, I would like it to place the selected inspiration images in the Google Doc template. I'm not sure if there's any way to do this, since it just exports the text value. I have used a basic Google Apps Script to output to the document from Google Sheets, but since the response doesn't place the image into Google Sheets, it will only place the text value associated with the image into the Google Doc. Does anyone know a way to have an image placed, corresponding to the text selected? Would getResponseForItem(item) work to pull the image?
function newLeadAutoFill(e) {
var timestamp = e.values[0];
var firstName = e.values[1];
var lastName = e.values[2];
var address = e.values[3];
var phone = e.values[4];
var email = e.values[5]
var budget = e.values[6];
var hardscapes = e.values[7];
var landscapes = e.values[8];
var shape = e.values[9];
var material = e.values[10];
var other = e.values[11];
var notes = e.values[12];
var design = e.values[16];
var templateFile = DriveApp.getFileById("doctemplate");
var templateResponseFolder = DriveApp.getFolderById("savelocation");
var copy = templateFile.makeCopy(lastName +', ' + firstName + '-' + timestamp, templateResponseFolder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText("{{FirstName}}",firstName);
body.replaceText("{{LastName}}",lastName);
body.replaceText("{{Address}}",address);
body.replaceText("{{Phone}}",phone);
body.replaceText("{{Email}}",email);
body.replaceText("{{Budget}}",budget);
body.replaceText("{{Hardscapes}}",hardscapes);
body.replaceText("{{Landscape}}",landscapes);
body.replaceText("{{Shape}}",shape);
body.replaceText("{{Material}}",material);
body.replaceText("{{Other}}",other);
body.replaceText("{{ClientNotes}}",notes);
body.replaceText("{{Design}}",design);
doc.saveAndClose();
}
I need the options shown below to be placed in a Google Doc in the {{Design}} placeholder with the images associated with each option. Note: Images in the form are not the final images and are being used only for testing purposes.
Template User input Result

Google Docs script editor trying to autogenerate an email from an autogenerated document

Everything I've found about this topic includes having a google sheet populate a google doc which then sends an email. I personally have pasted some code I found around the web into script editor of a doc. Now, upon opening a doc, the user is prompted to answer question boxes. the answers autopopulate a new document that is created. The script then calls for an email to be sent out.
So far, I have the prompts correct, the new document is created, with the correctly filled-in information from the prompt boxes. I have also gotten it to send an email to 1 address, which is all it is supposed to do. The subject line of the email is also correct. The problem is I want the new Google document that is created in the script to be the body of the email, and I just cannot figure out how to make that happen.
This is the code I have in script editor. I have tried numerous things in the last line to make the body of the new document populate the email body, with no luck. Can someone tell me the programming language for how to make this work please?
function myFunction() {
// Display a dialog box for each field you need information for.
var ui = DocumentApp.getUi();
//var response = ui.prompt('Enter Name', 'Enter sales person's name', ui.ButtonSet.OK);
var shiftResponse = ui.prompt('Enter shift, i.e. 7-3 or 3-11');
var peersResponse = ui.prompt('Enter peers on shift');
var participantsResponse = ui.prompt('Enter names of face to face encounters');
var phonelogResponse = ui.prompt('Enter names of people we called on phone log');
var filescreatedResponse = ui.prompt('Enter names of people we created files for');
var notesResponse = ui.prompt('Enter any notes about shift');
var cleanResponse = ui.prompt('Was Crisis Center Cleaned? Enter yes or no');
var authorResponse = ui.prompt('Enter your name');
var date = Utilities.formatDate(new Date(), "GMT", "MM/dd/yyyy");
//Make a copy of the template file
var documentId = DriveApp.getFileById('1lXTJPvwlJrXkRJ807daFsFbfaiC_wl7EAQ4giixLeEc').makeCopy().getId();
//Rename the copied file
DriveApp.getFileById(documentId).setName(date + " " + shiftResponse.getResponseText() + ' Shift Report');
//Get the document body as a variable
var body = DocumentApp.openById(documentId).getBody();
//Insert the entries into the document
body.replaceText('##date##', date);
body.replaceText('##shift##', shiftResponse.getResponseText());
body.replaceText('##peers##', peersResponse.getResponseText());
body.replaceText('##participants##', participantsResponse.getResponseText());
body.replaceText('##phonelog##', phonelogResponse.getResponseText());
body.replaceText('##filescreated##', filescreatedResponse.getResponseText());
body.replaceText('##notes##', notesResponse.getResponseText());
body.replaceText('##clean##', cleanResponse.getResponseText());
body.replaceText('##author##', authorResponse.getResponseText());
MailApp.sendEmail("jason.chrystal#voicesofhopececilmd.org", "Shift Report", body);
}
As it reads in the documentation:
The replaceText methods expects a regex pattern value as the first parameter:
https://developers.google.com/apps-script/reference/document/body#replacetextsearchpattern,-replacement
Also the last parameter of the MailApp.sendMail parameter expects a string and you are giving it a body class object.
Change your first parameter to a correct matching regex pattern and your code will work just fine.
body.replaceText(/^##date##$/, date);
body.replaceText(/^##shift##$/, shiftResponse.getResponseText());
body.replaceText(/^##peers##$/, peersResponse.getResponseText());
etc...
-- regex not tested.
If you are not comfortable with regular expressions you can use body.setText() as an alternative like so:
var oldBodyText = body.getText();
body = body.setText(oldBodyText.replace('##date##', date));
oldBodyText = body.getText();
body = body.setText(oldBodyText.replace('##shift##', shiftResponse.getResponseText()));
oldBodyText = body.getText();
body = body.setText(oldBodyText.replace('##peers##', peersResponse.getResponseText()));
etc...
// And then the last lines:
var newBody = body.getText();
MailApp.sendEmail("jason.chrystal#voicesofhopececilmd.org", "Shift Report", newBody);

Sending Autoreponse Email Script on Form Submit

I've used a script in another spreadsheet that emails me whenever someone submits a form. It emails me with a few answers to important questions as well as a link to to view the full response on the spreadsheet.
Here is my original code that works:
function Outreach_FormMailer(e) {
var recipient = "email#gmail.com";
var timestamp = e.values[0];
var name = e.values[1];
var subject = e.values[1]+" completed a Report for "+e.values[3]
var dates = e.values[7];
var goalMet = e.values[9]
var goalFocus = e.values[10]
var hyperlink = "myawesomelink.com"
htmlBody = name+' just completed the O/R Report for these dates: '+dates+'<br><br>Form completed on: '+timestamp+'<br>Was the goal met? '+goalMet+'<br>What was the goal focus? '+goalFocus+
'<br><br>View the Form:Click Here';
MailApp.sendEmail(recipient, subject, htmlBody, {htmlBody:htmlBody});
}
I wanted to use this code for a new form with different questions, so I edited the code to just correspond to the correct qeustions.
This is the code that doesn't work:
function Team_ApplicationMailer(e) {
var recipient = "email#gmail.com";
var timestamp = e.values[0];
var name = e.values[3];
var subject = e.values[1]+' filled out the Teams Application Form!' ;
var startdate = e.values[12];
var enddate = e.values[13]
var Focus = e.values[19]
var hyperlink="myawesomelink.com"
htmlBody = name+' from: '+e.values[1]+'just completed the Teams Application Form for these dates: '+startdate+' to '+enddate+'<br><br>Form completed on: '+timestamp+'<br><br>View the Form:Click Here';
MailApp.sendEmail(recipient, subject, htmlBody, {htmlBody:htmlBody});
}
I've done several test emails and for some reason, this version of the script will not work. I am adding this script to a form that already has responses on the spreadsheet. Would that make a difference? Really not sure what I did wrong in transferring the code to a different spreadsheet.
Thanks for the comments guys. I actually realized the above code does work as is. I forgot that I setup a filter in Gmail that was sending the autoresponse email to a folder I didn't see instead of the inbox. No problem with the code, I just forgot to check the right place the email was sent to.

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];
...

Google Forms Complex Email Send on Form Submit with Script

I have this right now as a script to send an email to myself as a test showing that there is a new application submitted, but I am looking to have a full-fledged email sent to our HR department giving the name of every field following by a : and a space then what their answer was. I know you can do this and have found a script that I tried to get to work, but it kept failing and the developer was no help in trying to help me fix it. I really would love to get this done for my HR department so that we can move on from creating a new application. Here is my code so far, I removed my email for privacy issues:
function sendFormByEmail(e){
var email = "emailgoeshere";
var subject = "A New Employment Application has been Submitted";
var message = "A New Application Has Been Submited. Please go to the spreadsheet for more details.";
MailApp.sendEmail(email, subject, message);
}
Thanks again!
Or you could try this very simple one :(read carefully comments in the script)
function sendFormByEmail(){
var email = "email adress comes here";
var subject = "A New Employment Application has been Submitted";
var message = "A New Application Has Been Submited. Please find the details below :";
var row = SpreadsheetApp.getActiveSpreadsheet().getLastRow();// assuming data is on the last row of the spreadsheet
var messagebody=createmessage(row);
MailApp.sendEmail(email, subject, message+messagebody);
}
//
function createmessage(row){
var sh = SpreadsheetApp.getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lastCol = ss.getLastColumn();
var LF= "\r\n"
var body = LF
var headers = sh.getRange(1,1,1,lastCol).getValues();
var data = sh.getRange(row,1,1,lastCol).getValues();
for(nn=0;nn<headers[0].length;++nn){
body+=headers[0][nn]+" : "+data[0][nn]+LF
}
Logger.log(body)
return body
}
//
//eof
As mentionned, data coming from the form must be on last row of data in the sheet and there must be some data to check how it works otherwhise answers=questions.
I've developed a script that might help you, it's called FormEmailer. You can find it in the Script Gallery or grab the code on its site.