Reputation: 1
How can I manipulate this line of code so that I can make a new folder based on the response in the google form. I have a field called "Name". I want it so that it not only goes into a Parent folder, but that it creates a new folder with the "Name" of the customer.
How can I do that with the following code?
Google script:
const initialize = () => {
const form = FormApp.getActiveForm();
ScriptApp.newTrigger("onFormSubmit").forForm(form).onFormSubmit().create();
};
const onFormSubmit = ({ response } = {}) => {
try {
// Get a list of all files uploaded with the response
const files = response
.getItemResponses()
// We are only interested in File Upload type of questions
.filter(
(itemResponse) =>
itemResponse.getItem().getType().toString() === "FILE_UPLOAD"
)
.map((itemResponse) => itemResponse.getResponse())
// The response includes the file ids in an array that we can flatten
.reduce((a, b) => [...a, ...b], []);
if (files.length > 0) {
// Each form response has a unique Id
const subfolderName = response.getId();
const parentFolder = DriveApp.getFolderById(PARENT_FOLDER_ID);
const subfolder = parentFolder.createFolder(subfolderName);
files.forEach((fileId) => {
// Move each file into the custom folder
DriveApp.getFileById(fileId).moveTo(subfolder);
});
}
} catch (f) {
Logger.log(f);
}
};
Upvotes: 0
Views: 326
Reputation: 64082
You should change the function that you create your trigger with to something like this:
function initialize() {
const form = FormApp.getActiveForm();
const ts = ScriptApp.getProjectTriggers().map(t=>t.getHandlerFunction());
if(!~ts.indexOf('onFormSubmit')) {
ScriptApp.newTrigger("onFormSubmit").forForm(form).onFormSubmit().create();
}
}
So that you don't create multiple triggers.
function onFormSubmit(e) {
try {
var subfolderName;
const files = e.response.getItemResponses().filter(itemResponse => itemResponse.getItem().getType().toString() === "FILE_UPLOAD").map((itemResponse) => itemResponse.getResponse()).reduce((a, b) => [...a, ...b], []);
e.response.getItemResponses().forEach(r => { if (r.getItem().getTitle() == 'Hold') { subfolderName = r.getResponse(); } });
if (files.length > 0) {
const parentFolder = DriveApp.getFolderById(PARENT_FOLDER_ID);
const subfolder = parentFolder.createFolder(subfolderName);
files.forEach((fileId) => {
DriveApp.getFileById(fileId).moveTo(subfolder);
});
}
} catch (f) {
Logger.log(f);
}
};
I think that will work but I must admit that I do most of my form coding in the spreadsheet.
Upvotes: 1