I was recently asked me if I knew a way to create custom branching in Google Forms. The scenario was they had a list of employee names in a Google Sheet which they wanted to turn into a Google Form drop-down list which when selected would redirect the respondent to their own section of the form.
The trick to doing this is the order you call the various form methods. The pseudocode for this goes something like:
- Add a form
ListItem
(if you are selecting an existingListItem
the order you do this is less important) - Loop through data from Google Sheet
- Add
PageBreakItem
(you can set section details like title and text at this point) - Push returned
PageBreakItem
to an array and.setGoToPage()
(so the respondent doesn’t go to another section) - Add any additional questions to the section for the respondent
- Add
.setChoices()
from the array for theListItem
The example code I gave for this is below and you can copy this Google Sheet with the code and bound form:
function updateForm() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var names = doc.getSheetByName('Data');
var form = FormApp.openByUrl(doc.getFormUrl());
// Adding a break and setting up the select list
var page1 = form.addPageBreakItem()
.setTitle('Employee Name');
var item = form.addListItem();
// getting two columns of data from our sheet (name and url)
var data = names.getRange(2, 1, names.getLastRow() - 1, 2).getValues();
var pages = []; // for collecting the choices in the list item
for (var n=0; n < data.length; n++){
var empName = data[n][0]; // name
var editUrl = data[n][1]; // url
// making a section for employee
var newPage = form.addPageBreakItem()
.setTitle(empName)
.setHelpText(editUrl);
// push our choice to the list select
pages.push(item.createChoice(empName,newPage));
// sets the section to submit after completing (rather than next employee section)
newPage.setGoToPage(FormApp.PageNavigationType.SUBMIT)
// if you need any questions for the employee in answer add them here e.g.
var sectionQ1 = form.addTextItem()
.setTitle('Question for '+empName);
}
// adding each of the employees to our select list
item.setTitle('Select')
.setChoices(pages);
}
This code is very basic and you would probably need to modify some of this to make more friendly but hopefully it is a useful starting point