Google Forms to Google Doc Journal Entries

A teacher requested the following for weekly journal submissions by students.

  1. Whatever is submitted is only viewable to the submitting student and the faculty member
  2. Submissions are not able to be edited after they are submitted (by the student)
  3. All of the submissions (for each student) can be viewed in one location by scrolling. (Something like one long document.)
  4. And whatever submission functionality is used can be linked to/embedded from Canvas as this will be the “hub” for all of his course resources.

My proposed solution is to have a Google Form interaction create a doc for each student and append their entries. The student will get view-only rights to the document. The video gives a pretty decent overview and the script is pretty well commented. The general concepts would be useful in other Google App Script scenarios.

This is the Google Script that makes it work.

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){
  const parentFolder = DriveApp.getFolderById('1VAmbtf1p1bF9vEOy7K_n9adtiC2wO8Lq');
  let exists = checkFileExistsInFolder(parentFolder, fileName);
  //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);
    makeJournalEntry(fileId,title,content); 
  } else {
      let files = parentFolder.getFilesByName(fileName);
      if (files.hasNext()) {
        let file = files.next();
        let fileId = file.getId();
      makeJournalEntry(fileId,title,content); 
    }
  }
 
}

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;
  }
}

Leave a Reply