问题
I have a Google form, which writes response data to a spreadsheet containing a script that is supposed mail the form-filler with his/her answers to the form.
I had success with e.values
before, and the mail generated just fine. Now there seems to be some problems, as empty answers are skipped, meaning that e.values[9]
for example becomes actually column 9, instead of 10, as it used to be (in the spring of 2014, at least). So if there are one or more fields left empty the following answers move backward in the array one or more steps, depending on the number of questions left empty. Behaviour like this wreaks havoc in carefully planned scripts!
I also tried to use namedValues
, but it can't tolerate empty fields either!
Does anybody know of a work around? I'd appreciate ideas.
回答1:
That open issue has been marked Working as intended. So no help there.
Here's a work-around. Also available in this gist.
Example
function onFormSubmit(e) {
fixFormEvent( e );
...
}
fixFormEvent( e )
/**
* Force blank reponses into event object's values property, so that the value's index
* correctly reflects the question order. (With "new Sheets" + "new Forms", blank responses
* are skipped in the event object.
*
* see http://stackoverflow.com/a/26975968/1677912
*
* @param {event} e Event received as a Spreadsheet Form object. The event's value
* property will be modified by this function.
* @return {event} The same event, for chaining
*/
function fixFormEvent( e ) {
var ss = SpreadsheetApp.getActive();
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
var resp = [e.namedValues["Timestamp"]];
for (var i=0; i<items.length; i++) {
switch (items[i].getType()) {
case FormApp.ItemType.IMAGE:
case FormApp.ItemType.PAGE_BREAK:
case FormApp.ItemType.SECTION_HEADER:
// Item without a response - skip it
break;
case FormApp.ItemType.CHECKBOX:
case FormApp.ItemType.DATE:
case FormApp.ItemType.DATETIME:
case FormApp.ItemType.DURATION:
case FormApp.ItemType.GRID:
case FormApp.ItemType.LIST:
case FormApp.ItemType.MULTIPLE_CHOICE:
case FormApp.ItemType.PARAGRAPH_TEXT:
case FormApp.ItemType.SCALE:
case FormApp.ItemType.TEXT:
case FormApp.ItemType.TIME:
// If item has a response, append it to array. If not, append blank.
var itemTitle = items[i].getTitle();
var type = items[i].getType();
if (itemTitle === "") throw new Error( "Untitled item" );
var itemResp = [];
if (itemTitle in e.namedValues) {
itemResp = e.namedValues[itemTitle];
}
resp.push( itemResp );
break;
default:
Logger.log( "Unknown item type, index=" + items[i].getIndex() );
break;
}
}
e.values = resp;
return e; // For chaining
}
回答2:
Can confirm this behaviour, and there is an open issue (at the time of this answer) for this.
As for a work around, could you process the namedValues object to work out which values are missing?
来源:https://stackoverflow.com/questions/25938213/e-values-in-google-forms-skips-empty-answers-is-there-a-workaround