I tried to accomplish exactly the same (list with products to select from), but I couldn't make it work with your final code example. Here's mine, with detailed instructions. Just for anybody who is landing on this page and is looking for a working code.
(Menu names might differ from yours, because I'm using a non-English Google Forms, and I'm just guessing the translations here.)
1) Create a new form, and create a new radio button based question (multiple choice) (In this example, I use the question name: "Select a product"). Don't add any options to it. Save it.
2) Open the spreadsheet where the responses are going to be stored, and add a new sheet in it (name: "inventory")
3) Fix the first row (A) of the inventory sheet, and put in A1: "Select a product"
4) Put in column A all the products you want to appear in the form
5) Open the form editor again, and go to tools > script editor
6) Paste this code in the editor, put in your form and spreadsheet ID's (3x) and save it.
var LIST_DATA = [{title:"Select a product", sheet:"inventory"}];
function updateLists() {
//var form = FormApp.getActiveForm();
var form = FormApp.openById("paste_ID_of_your_FORM_here");
var items = form.getItems();
for (var i = 0; i < items.length; i += 1){
for (var j = 0; j < LIST_DATA.length; j+=1) {
var item = items[i];
if (item.getTitle() === LIST_DATA[0].title){
updateListChoices(item.asMultipleChoiceItem(), LIST_DATA[0].sheet);
break;
}
}
}
}
function updateListChoices(item, sheetName){
var inventory = (SpreadsheetApp.openById("paste_ID_of_your_RESPONSE_SHEET_here")
.getSheetByName("inventory")
.getDataRange()
.getValues());
var selected = (SpreadsheetApp.openById("paste_ID_of_your_RESPONSE_SHEET_here")
.getSheetByName("responses")
.getDataRange()
.getValues());
var choices = [];
var selectedReal = [];
for (var i = 0; i< selected.length; i+=1){
selectedReal.push(selected[i][1])
}
for (var i = 1; i< inventory.length; i+=1){
if(selectedReal.indexOf(inventory[i][0])=== -1){
choices.push(item.createChoice(inventory[i][0]));}
}
if (choices.length < 1) {
var form = FormApp.getActiveForm();
form.setAcceptingResponses(false);
} else {
item.setChoices(choices);
}
}
7) With the code editor open, go to Resources > Create triggers and create these two triggers. They need to appear in this order:
- updateLists - from form - sending
- updateLists - from form - opening
Now you're good to go. If you open the form editor, the products added in the inventory sheet will appear as options.
Every time a product is chosen, it will disappear from the form. To reset all the chosen products, go to the form editor, and choose Responses > Remove all responses. You might need to remove all responses from the responses sheet manually as well (Don't know why, but that happened to me). After that, you need to manually run the updateLists script in the code editor.