Form notification email not populating all information

82 views
Skip to first unread message

Alves Simms

unread,
Aug 22, 2025, 5:04:00 AMAug 22
to Google Apps Script Community
Hello All,

I have the following script that was previously working but now does not display all response information in the email notification sent out. Specifically what happens is that all responses show up as "N/A" with the exception of the courtroom question, which does display in the email.  A sample of the email out put is also included below.  
Can someone please help me understand why only the courtroom response gets carried through.  I can confirm that all information is present in the responses sheet, they just don't get displayed in the email notification.  I have no prior experience with Google App Script and the last thing I coded was 20+ years ago.  I appreciate any assistance that can be provided.

Thank you

function onFormSubmit(e) {


  var response = e.namedValues;

  var dropdownSelection = response['Courtroom/Investigator'][0];


  var emailSubject = 'New Investigator Request Form Submission';


// Questions from the form

  var questionOrder = [


    'Attorney Name',


    'Client Name',


    'Charge',


    'Courtroom/Investigator',


    'Court Date:',


    'Case Narrative:',


    'Action Items-List due dates for each:',


  ];


  var emailBody = 'A new form has been submitted to Test. Details:\n\n';


  for (var i = 0; i < questionOrder.length; i++) {


    var question = questionOrder[i];


    var answer = response[question][i] ? response[question][0] : 'N/A';


    emailBody += question + ': ' + answer + '\n\n';


  }


var emailMap = {

// Emails sent to the following recipients based on which room is chosen on the form

    'Courtrooms #1 and JDR #1': 'som...@somewhere.org',
    'Courtroom #3 and JDR #3': 'someone@somewhere.org',
    'Court Room 208 and JDR #2': 'someone@somewhere.org',
    'Courtroom 210 and JDR #4': 'som...@somewhere.org',
    'JDR - Courtroom #5 ONLY': 'som...@somewhere.org',

};


  if (emailMap.hasOwnProperty(dropdownSelection)) {
    MailApp.sendEmail( emailMap[dropdownSelection], emailSubject, emailBody);
  } else {


 Logger.log('Warning: dropdownSelection ' + dropdownSelection + ' not found in emailMap');


  }


}

Sample Email displays this in the body:

A new form has been submitted. Details:

Attorney Name: N/A

Client Name: N/A

Charge: N/A

Courtroom/Investigator: Courtroom #3 and JDR #3

Court Date: N/A

Case Narrative: N/A

Action Items-List due dates for each: N/A

Larry Grenevitch

unread,
Aug 23, 2025, 4:41:12 AMAug 23
to Google Apps Script Community
The first thing you need to establish is that "e" the event variable has all of your data and is not being cut off.

I asked Gemini in AIstudio how to get the raw text of the event, below are the options it offered.  What you may need to do is identify the row that was added, and then directly access that row in the spreadsheet using Apps Script to pull the data.

The e parameter in your onFormSubmit(e) function in Google Apps Script is an event object that contains information about the form submission. To see the raw text or structure of this event object, you can use Logger.log() or console.log().

Here's how you can do it:

function onFormSubmit(e) {
// Log the entire event object to see its structure and content. 

Logger.log(e);

// You can also stringify it to get a JSON representation,
// which can be very helpful for understanding nested properties. 

Logger.log(JSON.stringify(e, null, 2));

// If you're specifically interested in the form responses,
// you can log those as well. The structure might vary slightly
// depending on whether your form is directly linked to a Google Sheet
// or if it's a standalone Google Form.

// For a form submission directly to a Google Sheet, 'e.values' might be available:
  if (e.values) {
    Logger.log("Form Values (e.values):");
    Logger.log(e.values);
  }
}

Gary Odums

unread,
Aug 23, 2025, 4:41:19 AMAug 23
to Google Apps Script Community
Hi,

In the original code, the i'th item was being referenced in the namedValues array that belongs to the event. The iteration counter i was instantiate to traverse the questionOrder array and not the namedValues array.

This condition is failing because of the use of the iteration counter i in this condition:
var answer = response[question][i] ? response[question][0] : 'N/A';

To fix this, change the line to reference 0 instead of i:
var answer = response[question][0] ? response[question][0] : 'N/A';

The new code would reference the first (0'th) item in the namedValues for the question response.


Hope this helps

Kildere S Irineu

unread,
Aug 27, 2025, 2:23:20 PM (11 days ago) Aug 27
to google-apps-sc...@googlegroups.com

A Solução Definitiva (Análise e Correção do Script)

O problema no seu script é sutil, mas crítico, e está concentrado nesta única linha dentro do loop:

var resposta = resposta[pergunta][i] ? resposta[pergunta][0] : 'N/A';

Existem dois erros fatais acontecendo aqui que causam o comportamento que você está vendo:

  1. Sobrescrita de Variável (O Erro Principal): Você tem uma variável chamada resposta que, antes do loop, guarda todos os seus dados (e.namedValues). Dentro do loop, você declara outra variável com o mesmo nome (var resposta). Na primeira vez que o loop roda, ele funciona. Mas na segunda vez, a variável resposta original já foi destruída e substituída por uma string (a resposta da primeira pergunta). Qualquer tentativa subsequente de acessar resposta['Nome do Cliente'] falhará, pois você está tentando tratar uma string como um objeto, resultando em "N/A" para todas as perguntas restantes.

  2. Índice Incorreto: Você está usando resposta[pergunta][i]. O i é o contador do seu loop (0, 1, 2, 3...). No entanto, o valor de e.namedValues para cada pergunta é um array que quase sempre tem apenas um elemento, no índice [0]. Portanto, quando i for 1, a expressão resposta[pergunta][1] será undefined, fazendo com que a lógica sempre retorne "N/A".

O Código Corrigido

Para resolver isso, precisamos usar nomes de variáveis diferentes e o índice correto. O código abaixo está corrigido, é mais legível e mais seguro.

Substitua sua função onFormSubmit por esta:

JavaScript
function onFormSubmit(e) {
  // Use um nome de variável claro para todas as respostas do formulário.
  var respostasDoFormulario = e.namedValues;

  var dropdownSelection = respostasDoFormulario['Tribunal/Investigador'][0];
  var emailSubject = 'Envio de formulário de solicitação de novo investigador';

  // As perguntas do formulário (sem alterações aqui)
  var questionOrder = [
    'Nome do Advogado',
    'Nome do cliente',
    'Cobrar',
    'Tribunal/Investigador',
    'Data do Tribunal:',
    'Narrativa do caso:',
    'Itens de ação - Liste as datas de vencimento para cada:',
  ];

  var emailBody = 'Um novo formulário foi enviado para Teste. Detalhes:\n\n';

  // Loop corrigido para construir o corpo do e-mail

  for (var i = 0
; i < questionOrder.length; i++) {
    var pergunta = questionOrder[i];
    var respostaDaPergunta = 'N/A'; // Define um padrão 'N/A'

    // Verifica se existe uma resposta para a pergunta atual no objeto de respostas
    if (respostasDoFormulario[pergunta]) {
      // Se existir, pega o primeiro (e único) valor da resposta
      respostaDaPergunta = respostasDoFormulario[pergunta][0];
    }
    
    emailBody += pergunta + ': ' + respostaDaPergunta + '\n\n';
  }

  var emailMap = {
    // E-mails enviados para os seguintes destinatários com base na sala escolhida no formulário
    'Tribunais #1 e JDR #1': 'som...@somewhere.org',
    'Tribunal nº 3 e JDR nº 3': 'alguém...@algumlugar.org',
    'Sala do Tribunal 208 e JDR #2': 'alguém...@algumlugar.org',
    'Tribunal 210 e JDR #4': 'som...@somewhere.org',
    'JDR - SOMENTE Sala do Tribunal nº 5': 'som...@somewhere.org',
  };

  if (emailMap.hasOwnProperty(dropdownSelection)) {
    MailApp.sendEmail(emailMap[dropdownSelection], emailSubject, emailBody);
  } else {
    Logger.log('Aviso: dropdownSelection "' + dropdownSelection + '" não encontrado no emailMap');
  }
}

Por que esta solução funciona:

  1. Nomes de Variáveis Claros: A variável que contém todas as respostas agora se chama respostasDoFormulario. A variável para a resposta de cada pergunta dentro do loop se chama respostaDaPergunta. Elas nunca entram em conflito.

  2. Lógica Segura: Em vez de uma linha complexa, a lógica agora é simples:

    • Primeiro, verifica se uma resposta para a pergunta existe (if (respostasDoFormulario[pergunta])). Isso evita erros se uma pergunta não for obrigatória e for deixada em branco.

    • Se existir, ele sempre pega o primeiro elemento ([0]), que é o correto.

  3. Resultado Final: O loop agora processa cada pergunta corretamente, usando o objeto respostasDoFormulario original em cada iteração, resultando em um e-mail com todos os dados preenchidos.


--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/google-apps-script-community/582d2138-c552-42f2-abfa-1b0804fccdc6n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages