multiple folders created on form submission - javascript

the script running in the background to a google form is returning a new folder and email for every question answered instead of just 1 folder and 1 email.... can anybody help to see where i went wrong!
function onSubmit() {
var form = FormApp.openById('123456789abcdefghij');
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var itemResponses = formResponse.getItemResponses();
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
Logger.log('Response #%s to the question "%s" was "%s"',
(i + 1).toString(),
itemResponse.getItem().getTitle(),
itemResponse.getResponse());
var DriveFolder = DriveApp.getFolderById("0B2eMBrrkabcdefghij");
var foldername = itemResponses[2].getResponse();
var folderpath = DriveFolder.createFolder(foldername).getUrl();
var to = itemResponses[1].getResponse();}
MailApp.sendEmail(
to,"Change Management Request", "Thank you for Submitting Step 1. Please fill out Step 2 (https://drive.google.com/open?id=0B2eMBrrkabcdefji) and upload to" +folderpath);
}}

Reformatting the code shows that the parts for creating the folder sending the mail are nested too deep within the for loops:
function onSubmit() {
var form = FormApp.openById('123456789abcdefghij');
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var itemResponses = formResponse.getItemResponses();
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
Logger.log(
'Response #%s to the question "%s" was "%s"',
(i + 1).toString(),
itemResponse.getItem().getTitle(),
itemResponse.getResponse());
var DriveFolder = DriveApp.getFolderById("0B2eMBrrkabcdefghij");
var foldername = itemResponses[2].getResponse();
var folderpath = DriveFolder.createFolder(foldername).getUrl();
var to = itemResponses[1].getResponse();
}
MailApp.sendEmail(
to,
"Change Management Request",
"Thank you for Submitting Step 1. Please fill out Step 2 (https://drive.google.com/open?id=0B2eMBrrkabcdefji) and upload to" +folderpath);
}
}
Probably you want to move them out, but without knowing which field you want for calculating the folder name, I can only guess:
function onSubmit() {
var form = FormApp.openById('123456789abcdefghij');
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var itemResponses = formResponse.getItemResponses();
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
Logger.log(
'Response #%s to the question "%s" was "%s"',
(i + 1).toString(),
itemResponse.getItem().getTitle(),
itemResponse.getResponse());
}
}
var DriveFolder = DriveApp.getFolderById("0B2eMBrrkabcdefghij");
var folderAndToResponse = formResponses[formResponses.length - 1].getItemResponses();
var foldername = folderAndToResponse[2].getResponse();
var folderpath = DriveFolder.createFolder(foldername).getUrl();
var to = folderAndToResponse[1].getResponse();
MailApp.sendEmail(
to,
"Change Management Request",
"Thank you for Submitting Step 1. Please fill out Step 2 (https://drive.google.com/open?id=0B2eMBrrkabcdefji) and upload to" + folderpath);
}

Related

Certain number question being missed in regex

I have the following if statement that removes the first instances of a number followed by the period. However, I am noticing it is missing to catch some of them (ex. "16.", "23.", "24.", etc.) and not sure why.
Here is the function:
function quesCleanUp(ques){
//Checks the first instance of "." and removes it and the number
if(ques.match(/[0-9]\./g)?.length > 1){//(ques.match(/./g)?.length > 1){
var quesClean = ques.replace(/^[^\.]*\./, '').trim();
} else{
var quesClean = ques.trim();
}
return quesClean;
}
The following for loop extracts the question from the google form:
for (var i = 0; i < items.length; i++) {
var item = items[i];
switch(item.getType()) {
case FormApp.ItemType.MULTIPLE_CHOICE:
var question = item.asMultipleChoiceItem();
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "Multiple Choice";
var optns = [];
var answr;
var answers = question.getChoices();
answer_val = false;
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue().trim();
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr = answers[j].getValue().trim();
for(var x = 0; x < optns.length; x++){
if(answr == optns[x]){
answer_val = true;
break;
}
}
}
}
var multiJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON1: " + JSON.stringify(multiJSON));
constructedJSON[i+1] = multiJSON;
break;
case FormApp.ItemType.CHECKBOX:
var question = item.asCheckboxItem();
//var ques = question.getTitle().trim();//.replace(/\s/g, "");
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "CheckBox";
var optns = [];
var answr = [];
var answers = question.getChoices();
for (var j = 0; j < answers.length; j++) {
var clean = answers[j].getValue().trim();//replace(/\s/g, "");
optns.push(clean);
if(answers[j].isCorrectAnswer()){
answr.push(answers[j].getValue().trim());
}
}
var checkJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON2: " + JSON.stringify(checkJSON));
constructedJSON[i+1] = checkJSON;
break;
case FormApp.ItemType.PARAGRAPH_TEXT:
var question = item.asParagraphTextItem();
//var ques = question.getTitle().trim();//.replace(/\s/g, "");
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var question_type = "free response";
var optns = [];
var answr;
var paraJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON3: " + JSON.stringify(paraJSON));
constructedJSON[i+1] = paraJSON;
break;
case FormApp.ItemType.TEXT:
var question = item.asTextItem();
//var ques = question.getTitle().trim();
var question_type = "free response";
var ques = quesCleanUp(question.getTitle().trim());//replace(/\s/g, "");
var optns = "";
var answr = "";
var textJSON = makeJSON(ques, question_type, optns, answr);
console.log("JSON4: " + JSON.stringify(textJSON));
constructedJSON[i+1] = textJSON;
break;
}
The following example is the type of question 16. What is the meaning of life?
And the expected output: What is the meaning of life?
Try using /[0-9]+./g to catch more than one digit
As a quick fix, in the function quesCleanUp() try to change the line:
if(ques.match(/[0-9]\./g)?.length > 1){//(ques.match(/./g)?.length > 1){
With:
if (ques.match(/^[0-9]+\./g).length > 0) {
I suspect you got the downvotes because you posted the code with glared typos. It looks like you didn't even try to debug it first. And as the icing on the cake you accepted a wrong answer.
And probably the function can be boiled down to just one line:
const quesCleanUp = q => q.replace(/^\d+\./,'').trim();
Here is how it works:
var questions = ['1. aaa', '16. What', '23. That', 'No nums'];
const quesCleanUp = q => q.replace(/^\d+\./,'').trim();
questions.forEach(q => console.log(quesCleanUp(q)));
Expected output:
aaa
What
That
No nums

Receiving [Ljava.lang.Object in Apps Script (bringing attachment name from Gmail to Sheets)

Have been working on an Apps Script to bring Gmail message information (sender, subject, link, attachment) into a Google Sheet, but not able to bring the title of the attachment over successfully (attachment name field in Google Sheet reads like [Ljava.lang.Object;#127afe9; it appears to be related to the attachments array, but I cannot figure it out. Have tried the solutions offered in What does "[Ljava.lang.Object;#" mean?, but no luck.
function emailToSheet() {
var label = GmailApp.getUserLabelByName('New TODO'); // Find messages with label
var changeLabel = GmailApp.getUserLabelByName('TODO'); // Change message label to
var ss = SpreadsheetApp.openById('xxxx'); // Append to spreadsheet
var sh = ss.getSheetByName("Email"); //On this sheet
var threads = label.getThreads();
for (var i=0; i<threads.length; i++){
var messages = threads[i].getMessages();
for (var j=0; j<messages.length; j++) {
var sent = messages[j].getDate();
var from = messages[j].getFrom();
var subject = messages[j].getSubject();
// Get attachment name
var attachments = messages[j].getAttachments();
var attachmentName = [];
for (var k=0; k<attachments.length; k++) {
var attachmentName = attachments[k].getName();
}
var messageId = messages[j].getId();
var messageUrl = "https://mail.google.com/mail/u/0/#inbox/" + messageId;
ss.appendRow([sent, from, subject, attachmentName, messageUrl])
}
threads[i].removeLabel(label);
threads[i].addLabel(changeLabel);
}
}
I'm thinking that you want this:
var attachmentName = [];
for (var k=0; k<attachments.length; k++) {
var attachmentName = attachments[k].getName();
}
to be this:
var attachmentName = [];
for (var k=0; k<attachments.length; k++) {
attachmentName.push(attachments[k].getName());
}
and maybe this:
ss.appendRow([sent, from, subject, attachmentName, messageUrl])
to be this:
ss.appendRow([sent, from, subject, attachmentName.join(" "), messageUrl])

Forward to different users depending on labels - Gmail Apps Script

I am trying to create an Apps Script for Gmail, so that all messages labelled product-related and product-a are forwarded to the producta#gmail.com address, and all messages labelled "product-related" and product-b are forwarded to the productb#gmail.com address.
The script will be launched via a card, so there is no need for more automation.
Here's the code I did:
function testforward1() {
var label = "product-related";
//var interval = 2000;
//var date = new Date();
//var timeFrom = Math.floor(date.valueOf()/1000) - 60 * interval;
var threads = GmailApp.search('label:' + label);
for (var i = 0; i < threads.length; i++) {
if (label == "product-a" && "product-related") {
var recipient = 'producta#gmail.com';
var messages = threads[i].getMessages();
//var attachment = messages[i].getAttachments();
for (var j = 0; j < messages.length; j++) {
var body = messages[j].getBody();
messages[j].forward(recipient, {
htmlBody: body
});
}
}
if (label == "product-b" && "product-related") {
var recipient1 = 'productb#gmail.com';
var messages1 = threads[i].getMessages();
//var attachment1 = messages1[i].getAttachments();
for (var j = 0; j < messages1.length; j++) {
var body1 = messages1[j].getBody();
messages1[j].forward(recipient1, {
htmlBody: body1
});
}
}
}
}
I guess I did something wrong with the variables, but I'm a total beginner with Google Apps Scripts, and I already spent more than 10 hours on this, with no success.
I got no email transferred with this, but the execution gives no error. And I was wondering if the var label = "product-related"; should be replaced with something else?
I will be grateful if you could give me some help on this!
I made it work (I think)! :)
function testforward1() {
var threadsa = GmailApp.search('label: product-related label: product-a');
for (var i = 0; i < threadsa.length; i++) {
var recipient = 'producta#gmail.com';
var messages = threadsa[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var body = messages[j].getBody();
messages[j].forward(recipient,{htmlBody: body});
}
}
var threadsb = GmailApp.search('label: product-related label: product-b');
for (var i = 0; i < threadsb.length; i++) {
var recipient = 'productb#gmail.com';
var messages = threadsb[i].getMessages();
for (var j = 0; j < messages.length; j++) {
var body = messages[j].getBody();
messages[j].forward(recipient,{htmlBody: body});
}
}
}
Now I still have a few more functions to implement, but the basic forwarding function works, and it's the most important.

Can I do For loop on Google Script?

I was trying to put some information of my sheet in a array, to use in a graphic later. But this error keeps showing :(
Error: Syntax error (line 8, archive "Código")
function onOpen() {
var proposta = SpreadsheetApp.getActive().getSheetByName('Proposta de solução');
var ids = proposta.getRange('A10:A26');
var names = proposta.getRange('B10:B26');
var esforcos = proposta.getRange('F10:F26');
var name = [
for (var i = 0; i < 17; i++) {
names.getCell(i, 1).getValue();
}
]
var id = [
for(var j = 0; j < 17; j++) {
ids.getCell(j,1).getValue();
}
]
var esforco = [
for(var k = 0; k < 17; k++) {
esforcos.getCell(k,1).getValue();
}
]
}
This should get the results you want:
function onOpen() {
var proposta = SpreadsheetApp.getActive().getSheetByName('Proposta de solução');
var ids = proposta.getRange('A10:A26');
var names = proposta.getRange('B10:B26');
var esforcos = proposta.getRange('F10:F26');
var name = [];
var id = [];
var esforco = [];
for (var i = 0; i < 17; i++) {
name.push(names.getCell(i, 1).getValue());
id.push(ids.getCell(i, 1).getValue());
esforco.push(esforcos.getCell(i, 1).getValue());
}
}

Google Form Script Population

I am trying to populate a google form with questions scraped from a google sheet. Currently when I run my code I am getting the questions created, but only 25% or so actually have the string, the rest are simply blank. The questions that appear correctly change every time I run the script. It is seemingly random.
function formPopulation() {
var ss = SpreadsheetApp.openById("--");
var sheet = ss.getSheetByName('Tracker');
var auditTool = ss.getSheetByName('Audit Tool');
var validatorInfo = ss.getSheetByName('Validator Info');
//Sheet Info
var rows = auditTool.getLastRow(); //Number of Rows
var columns = auditTool.getLastColumn(); //Number of Columns
var startRow = 1;
var startColumn = 1;
var dataRange = auditTool.getRange(startRow, startColumn, rows, columns);
//getRange(first row of data, first column of data, last row of data, last column of data)
var data = dataRange.getValues();
//Sets working range of script
var form = FormApp.openById("--");
var item = form.addListItem();
var entityName = "";
var arrayOfEntities = [];
var newEntity = '';
for (var i = 4; i < columns; i++) {
//4 because that is where entity names begin
entityName = data[i][2];
Logger.log('entityName: ' + entityName);
newItem = item.createChoice(entityName);
arrayOfEntities.push(newItem);
};
item.setTitle("Select Entity").setChoices(arrayOfEntities);
var requirement = "";
var arrayOfRequirements = [];
var newRequirement = '';
for (var j = 5; j < rows; j++) {
//5 because that is where Requirements begin
if (data[0][j] != null) {
requirement = data[0][j];
if (requirement != "" || requirment != null){
requirement = "question #" + j;
Logger.log('requirement: ' + requirement);
form.addMultipleChoiceItem().setTitle(requirement).setChoiceValues(['Complete', 'Incomplete']);
};
};
};
};
The first question is supposed to be a multiple choice item where each 'entity' is an option. The remainder of the questions are supposed to be whether each 'requirement' is marked complete or incomplete.
Here is the spreadsheet I am working from
you have a typo:
if (requirement != "" || requirment != null){
should be 'requirement'
Here in last forloop
requirement = "question #" + j;
Please verify, is it ok ? or you should use
requirement = "question #" + j + ' ' +data[0][j];

Categories

Resources