Google Apps Script onFormSubmit Trigger: e.namedValues is always undefined/empty

37 views
Skip to first unread message

Stefan Geiger

unread,
Jul 7, 2025, 8:17:06 AMJul 7
to Google Apps Script Community

Hi everyone,

I'm encountering an extremely persistent and frustrating issue with Google Apps Script's onFormSubmit trigger. Despite extensive troubleshooting, I consistently receive a TypeError: Cannot read properties of undefined (reading 'Testfrage') error, indicating that the e.namedValues object is always undefined or empty when the script is triggered by a form submission.

Problem Description: My script is triggered by a Google Form submission. It's designed to take the value from a single "Short answer" question named Testfrage, insert it into a Google Docs template (where the placeholder is {{Testfrage}}), and then save the document as a PDF to Google Drive. The script is working fine in terms of creating the PDF and saving it, but the PDF contains placeholder values because no data from the form (e.namedValues) is being received. Even the e.timestamp from the event object appears to be invalid in the logs.

Minimal Script I'm using (causing the error):

JavaScript
function onFormSubmit(e) {
  // --- KONFIGURATION ---
  // BITTE HIER DEINE IDS EINFÜGEN:
  const TEMPLATE_DOC_ID = '1YDdIFzKTs-9SBllrz5Nb-VNdYgLXGln_8kssTXSgIxk'; // ID deiner Google Docs Vorlage
  const OUTPUT_FOLDER_ID = '1SS4j29lWjLeqVO-nZj1opvBvINovlo0r';   // ID des Ordners, wo PDFs gespeichert werden sollen

  // --- DATEN AUS DEM FORMULAR ABRUFEN ---
  // Hier wird direkt auf die Daten zugegriffen. Wenn 'e.namedValues' leer ist,
  // wird es hier zu einem Fehler kommen.
  const formResponses = e.namedValues;
  const testQuestionValue = formResponses['Testfrage'][0]; // <-- Achtung: 'Testfrage' muss der exakte Name deines Formularfeldes sein!

  // --- DATEINAMEN DEFINIEREN ---
  const fileName = `Einreichung_Testfrage_${new Date().getTime()}`;

  // --- GOOGLE DRIVE & DOCS OPERATIONEN ---
  const outputFolder = DriveApp.getFolderById(OUTPUT_FOLDER_ID);
  const templateDoc = DocumentApp.openById(TEMPLATE_DOC_ID);
 
  // Kopie der Vorlage erstellen
  const copyDoc = DriveApp.getFileById(TEMPLATE_DOC_ID).makeCopy(fileName, outputFolder);
  const newDoc = DocumentApp.openById(copyDoc.getId());
  const body = newDoc.getBody();

  // --- PLATZHALTER ERSETZEN ---
  body.replaceText(`{{Testfrage}}`, testQuestionValue);
  body.replaceText(`{{Timestamp}}`, new Date(e.timestamp).toLocaleString());

  // --- ALS PDF SPEICHERN UND ORIGINAL LÖSCHEN ---
  newDoc.saveAndClose(); // Änderungen in der Docs-Kopie speichern
  const pdfBlob = copyDoc.getAs(MimeType.PDF); // Docs-Kopie als PDF konvertieren
  outputFolder.createFile(pdfBlob).setName(`${fileName}.pdf`); // PDF im Ordner speichern

  // Die erstellte Google Docs Kopie in den Papierkorb verschieben.
  // Kommentiere die nächste Zeile aus, wenn du die .doc-Kopie behalten möchtest.
  copyDoc.setTrashed(true);
}

What I've already tried (and what the logs show):

  1. Brand New Google Forms and Apps Script Projects:

    • Created completely new forms (with just one "Testfrage" field).

    • Created new Apps Script projects linked to these new forms.

    • Result: Same error; e.namedValues is empty.

  2. Different Google Accounts:

    • Tested the entire setup (new form, new script, new template, new folder) using both a Google Workspace account and a separate personal Gmail account.

    • Result: The problem persists across both account types. This indicates it's not a Workspace admin setting issue.

  3. Multiple Web Browsers & Incognito Mode:

    • Performed tests across Chrome, Firefox, and Microsoft Edge, including in Incognito/Private Browse modes. Cleared browser cache and disabled extensions.

    • Result: The issue remains consistent, ruling out browser-specific problems, cache, or extensions.

  4. Full Script Authorization & Trigger Setup:

    • The script was fully authorized (granting Drive/Docs access).

    • The onFormSubmit trigger is correctly configured ("From forms" / "On form submit").

Consistent Log Output (from robust script version, which had more logging):

*** START DER SKRIPT-AUSFÜHRUNG *** Event-Objekt empfangen: {"authMode":"FULL","response":{},"source":{},"triggerUid":"[a numeric ID]"} Ist e.namedValues definiert? Nein Typ von formResponses (e.namedValues): object Anzahl der Felder in formResponses: 0 WARNUNG: formResponses (e.namedValues) ist leer oder nicht definiert. Keine Formulardaten extrahiert. --- ENDE DER DEBUG-LOGS --- PDF erfolgreich erstellt. *** ENDE DER SKRIPT-AUSFÜHRUNG ***

The logs clearly show that the e object itself, while present, does not contain the namedValues (or formData) property with the submitted answers. This happens despite filling out the form before submission. The PDF is created, but with placeholder data, as the script cannot access the form's input.

This seems to be a fundamental issue with how Google Forms is transmitting data to the onFormSubmit event. Has anyone experienced this or knows of a specific setting/bug that could cause this consistent behavior across accounts and environments? Any help or insights would be greatly appreciated.

Thank you!

Google Pony

unread,
Jul 10, 2025, 4:02:23 AMJul 10
to Google Apps Script Community

Hi Stefan,


Thank you for your detailed explanation and for sharing the steps you've already taken to troubleshoot the issue. I understand how frustrating this must be, especially since you've tried so many different approaches.


Possible Solution

Based on your description, it seems the issue might be related to how the trigger is being set up or how the form responses are being captured. Here are a few suggestions:


1. Ensure the Trigger is Correctly Bound to the Form

Sometimes, manually setting up the trigger (rather than relying on the automatic binding) can resolve issues.

Go to your Apps Script project:

Click on Triggers (clock icon on the left).

Remove any existing onFormSubmit triggers.

Add a new trigger manually:

Function to run: onFormSubmit

Event source: From form

Event type: On form submit

Click Save and authorize if prompted.


2. Verify the Form-Script Link

Ensure the script is attached to the correct form.

Open your Google Form → Responses → More (⋮) → Script Editor.

If the script opens in a new project, it means your original script wasn’t linked to the form.


3. Use e.response.getItemResponses() Instead of e.namedValues

Sometimes, e.namedValues may not populate correctly, but the raw responses are still accessible via e.response. Try modifying your script like this:

const onFormSubmit = (e) => {
  // --- KONFIGURATION ---
  const TEMPLATE_DOC_ID = '1YDdIFzKTs-9SBllrz5Nb-VNdYgLXGln_8kssTXSgIxk';
  const OUTPUT_FOLDER_ID = '1SS4j29lWjLeqVO-nZj1opvBvINovlo0r';

  // --- DATEN AUS DEM FORMULAR ABRUFEN (ALTERNATIVE METHODE) ---
  const itemResponses = e.response.getItemResponses();
  let testQuestionValue = "";
 
  for (let i = 0; i < itemResponses.length; i++) {
    const itemResponse = itemResponses[i];
    if (itemResponse.getItem().getTitle() === "Testfrage") {
      testQuestionValue = itemResponse.getResponse();
      break;
    }
  }

  // --- REST DES SKRIPTS (UNVERÄNDERT) ---
  const fileName = `Einreichung_Testfrage_${new Date().getTime()}`;
  const outputFolder = DriveApp.getFolderById(OUTPUT_FOLDER_ID);
  const templateDoc = DocumentApp.openById(TEMPLATE_DOC_ID);
 
  const copyDoc = DriveApp.getFileById(TEMPLATE_DOC_ID).makeCopy(fileName, outputFolder);
  const newDoc = DocumentApp.openById(copyDoc.getId());
  const body = newDoc.getBody();

  body.replaceText(`{{Testfrage}}`, testQuestionValue);
  body.replaceText(`{{Timestamp}}`, new Date(e.timestamp).toLocaleString());

  newDoc.saveAndClose();
  const pdfBlob = copyDoc.getAs(MimeType.PDF);
  outputFolder.createFile(pdfBlob).setName(`${fileName}.pdf`);
  copyDoc.setTrashed(true);
}


4. Test with a Simple Logging Script

To confirm whether the event object contains any data at all, try running a minimal debug script:

const onFormSubmit = (e) => {
  console.log("Event Object:", JSON.stringify(e, null, 2));
  console.log("Has namedValues?", !!e.namedValues);
  console.log("Has response?", !!e.response);
}

Check View → Logs in Apps Script after submitting a test form.

If the Issue Persists


If none of the above works, it might be worth:

Checking if the form is part of a Google Workspace domain with restricted permissions.

Trying a different Google Account (personal vs. Workspace).

Reporting the issue to Google Issue Tracker ([issuetracker.google.com](https://issuetracker.google.com/)) if it seems like a bug.


Let me know if any of these suggestions help or if you need further clarification!


Sincerely yours,
Sandeep Kumar Vollala
Consultant
LinkedIn Logo WhatsApp Logo
Reply all
Reply to author
Forward
0 new messages