Last active
August 26, 2024 17:39
-
-
Save woodwardtw/0fa05ffd126211b52d2a0b69ecd77d2e to your computer and use it in GitHub Desktop.
A Google Script for creating docs and journal entries from a form submission.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//this function is set to run on each form submit and is tied to the spreadsheet where the entries go | |
function onSubmit(){ | |
let sheet = SpreadsheetApp.getActiveSheet(); | |
let rows = sheet.getDataRange(); | |
let lastRow = rows.getLastRow(); | |
let email = sheet.getRange(lastRow,2).getValue(); | |
let atSymbol = email.search('@'); | |
let cleanEmail = email.substring(0,atSymbol); | |
let title = sheet.getRange(lastRow,3).getValue(); | |
let content = sheet.getRange(lastRow,4).getValue(); | |
makeStudentDoc(cleanEmail, title, content, email); | |
} | |
function makeStudentDoc(fileName, title, content, email){ | |
//The folder is hardcoded via the ID | |
const parentFolder = DriveApp.getFolderById('1VAmbtf1p1bF9vEOy7K_n9adtiC2wO8Lq'); | |
let exists = checkFileExistsInFolder(parentFolder, fileName);//checks for the Google Doc named after the student email | |
//make base document if it doesn't exist | |
if(!exists){ | |
const studentDoc = DocumentApp.create(fileName); | |
studentDoc.addViewer(email); | |
let fileId = studentDoc.getId(); | |
DriveApp.getFileById(fileId).moveTo(parentFolder);//move to parent folder | |
makeJournalEntry(fileId,title,content); //make journal entry | |
} else { | |
let files = parentFolder.getFilesByName(fileName);//get existing Google Doc | |
if (files.hasNext()) { | |
let file = files.next(); | |
let fileId = file.getId(); | |
makeJournalEntry(fileId,title,content); //make journal entry | |
} | |
} | |
} | |
function makeJournalEntry(fileId, title, content) { | |
let doc = DocumentApp.openById(fileId); | |
// Get the body of the document | |
let body = doc.getBody(); | |
//set title of entry | |
let weekTitle = body.appendParagraph(title); | |
// Set the heading style to H1 | |
weekTitle.setHeading(DocumentApp.ParagraphHeading.HEADING1); | |
// Append the paragraph content to the document | |
body.appendParagraph(content); | |
// Save and close the document just in case | |
doc.saveAndClose(); | |
} | |
//does document already exist? | |
function checkFileExistsInFolder(parentFolder, fileName) { | |
let files = parentFolder.getFilesByName(fileName); | |
if (files.hasNext()) { | |
//Logger.log('File exists'); | |
return true; | |
} else { | |
//Logger.log('File does not exist'); | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment