Google Apps Script for Forms: Want to send users s

2019-06-12 03:22发布

问题:

It is possible to ask users to write their email addresses in FORM and after that they recieve email with unique number?

I find out how to send automatic email to submitter here - http://www.labnol.org/internet/auto-confirmation-emails/28386/

But don't know how to send to him unique number each!

回答1:

you could try the above code to retrieve the unique id of the form response. But it's not sorted numbers(1,2,...). It's a unique random number generated by the form. my advice is not to try to build something starting to 1 and going further, as it's assynchronious you do not have the security to to have a sorted list of items. see here for details.

/**
* for a form with 2 question named "question 1" and "question 2"
* this function need to be associated directly to the form
* and it need to be associated to a trigger "on form submit"
* the "e" given as argument is generated by the form submit trigger
*/
function submitFormFunc(e) {
  var items = e.response.getItemResponses();
  var responses={};
  for(var i = 0; i< items.length; i++) {
   responses[items[i].getItem().getTitle()]=items[i].getResponse();
  }

  var responseTable = [];
  var responseIndex = ["Timestamp","ID","question 1","question 2"];
  responseTable.push(e.response.getTimestamp().toString());
  responseTable.push(e.response.getId());
  responseTable.push(responses["question 1"]); // my form have 2 questions named "question 1" and "question 2"
  responseTable.push(responses["question 2"]);
  responseTable.push(FormApp.getActiveForm().getResponse(e.response.getId()).getEditResponseUrl());
  SpreadsheetApp.openById("YOUR_SPREADSHEET_ID").appendRow(responseTable);
}

--EDIT--

if You want something shorter you can use the time stamp:

change (or add) responseTable.push(e.response.getTimestamp().toString()); for

responseTable.push(e.response.getTimestamp().getTime().toString());

or even shorter but a little less efficient:

you can add a line:

responseTable.push(generateUnique());

and add the function:

function generateUnique(){
  var vals =  SpreadsheetApp.openById("YOUR_SPREADSHEET_ID").getRange("A:A").getValues();
  var ids=[];
  for(var i in vals){
    ids.push(vals[0]);
  }
  var newId = Math.floor(Math.random()*100); // change 100 for something bigger if needed
  while(ids.indexOf(newId)>-1){
    newId = Math.floor(Math.random()*100);
  }
  Logger.log(newId);
  return(newId);
}