|
/** |
|
* Google Apps Script code to close a Google Form when it reaches a maximum number of responses. |
|
* Author: Jakub Andrýsek |
|
* Website: https://kubaandrysek.cz |
|
* Email: [email protected] |
|
* GitHub: https://github.com/JakubAndrysek |
|
* License: MIT |
|
* File: https://gist.github.com/JakubAndrysek/fbcdf78f7bc91d905d22350e7cbcdb31 |
|
*/ |
|
|
|
// Number of maximum responses you want to allow before closing the form |
|
const maxResponses = 42; |
|
const ownerEmail = "[email protected]"; // Email address for notifications |
|
const full = " (full)" |
|
|
|
// Triggered automatically when a form response is submitted. |
|
function onFormSubmit(e) { |
|
// Get the Google Form object |
|
var form = FormApp.getActiveForm(); |
|
var formId = form.getId(); |
|
|
|
// Get the actual number of responses the form has received so far |
|
var numResponses = form.getResponses().length; |
|
Logger.log(`${numResponses}/${maxResponses}`) |
|
|
|
// Check if the limit has been reached |
|
if (numResponses >= maxResponses) { |
|
Logger.log("This form has reached the maximum number of responses. Sorry, you can't sign up anymore.") |
|
// Display a message on the form |
|
form.setCustomClosedFormMessage('This form has reached the maximum number of responses. Sorry, you can\'t sign up anymore.'); |
|
|
|
// Append "(obsazeno)" to the title if it's not already there |
|
if (!form.getTitle().endsWith(full)) { |
|
form.setTitle(form.getTitle() + full); |
|
} |
|
|
|
// Also rename the file on Google Drive if needed |
|
var file = DriveApp.getFileById(formId); |
|
if (!file.getName().endsWith(full)) { |
|
file.setName(form.getTitle()); |
|
} |
|
|
|
Logger.log("Rename to: " + form.getTitle()); |
|
|
|
// Close the form to prevent more responses |
|
form.setAcceptingResponses(false); |
|
|
|
// Send an email notification to the form owner |
|
sendEmailToOwner(form); |
|
Logger.log("Email sent to the form owner."); |
|
} |
|
} |
|
|
|
// Sends an email to the form owner when the maximum limit is reached |
|
function sendEmailToOwner(form) { |
|
const title = DriveApp.getFileById(form.getId()).getName(); |
|
var subject = `Form "${title}" has reached the maximum number of responses`; |
|
var body = `Your Google Form "${title}" has reached the maximum number of responses (${maxResponses}). Further sign-ups are not allowed.`; |
|
|
|
// Send the email |
|
GmailApp.sendEmail(ownerEmail, subject, body); |
|
} |