-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcleanResponses.js
More file actions
74 lines (70 loc) · 2.35 KB
/
cleanResponses.js
File metadata and controls
74 lines (70 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Cleanup form responses - removing all forms that link to this sheet, and then removing all sheets named "Form Responses..."
* which would also remove any duplicates created during testing or leftover by interrupted processes.
*/
function cleanupFormResponses() {
deleteFormsLinkedToCurrentSpreadsheet();
deleteAllFormResponsesSheets();
}
/**
* Deletes all sheets in the active spreadsheet whose names start with "Form Responses".
*/
function deleteAllFormResponsesSheets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
sheets.forEach(function (sheet) {
if (sheet.getName().startsWith("Form Responses") || sheet.getName() === "Candidate Responses") {
Logger.log("Deleting sheet: " + sheet.getName());
ss.deleteSheet(sheet);
}
});
}
/**
* Deletes all forms that are linked to the current spreadsheet.
* Use with caution: this will permanently delete the forms from Drive.
*/
function deleteFormsLinkedToCurrentSpreadsheet() {
var forms = getFormsLinkedToCurrentSpreadsheet();
if (forms.length === 0) {
Logger.log("No forms are linked to this spreadsheet.");
return;
}
forms.forEach(function (file) {
try {
var form = FormApp.openById(file.getId());
form.removeDestination(); // Unlink the form from the spreadsheet
Logger.log(
"Unlinked form: " + file.getName() + " (" + file.getId() + ")"
);
} catch (e) {
Logger.log(
"Could not unlink form: " + file.getName() + " (" + file.getId() + ")"
);
}
Logger.log("Deleting form: " + file.getName() + " (" + file.getId() + ")");
file.setTrashed(true); // Moves to trash
});
Logger.log(forms.length + " form(s) unlinked and moved to trash.");
}
/**
* Returns an array of form file objects (from DriveApp) that are linked to the current spreadsheet.
*/
function getFormsLinkedToCurrentSpreadsheet() {
var ssId = SpreadsheetApp.getActiveSpreadsheet().getId();
var linkedForms = [];
var files = DriveApp.getFilesByType(MimeType.GOOGLE_FORMS);
while (files.hasNext()) {
var file = files.next();
try {
var form = FormApp.openById(file.getId());
var destId = form.getDestinationId();
if (destId && destId === ssId) {
linkedForms.push(file);
}
} catch (e) {
// Skip forms you can't open
continue;
}
}
return linkedForms;
}