如何在 Google Apps 脚本中将 Checkbox 和 Multiple Choice 的可选值放入预填表单中?

How to put the optional values of Checkbox and Multiple Choice in the prefilled form in Google Apps Script?

我正在使用 Google 表单作为自动化我的工作流程并从电子表格数据生成文档的工具。
为了避免输入所有数据两次,我尝试生成一个包含预填回复的表单 link。
我可以用这段代码来做到这一点(感谢@Mogsdad previous response) and it works well, except when I have an optional "other" field in Checkbox and Multiple Choice optional "other" field。在这种情况下,我没有得到这个可选值,这正是我想要的,所以用户不必重新输入它。

我使用的代码是这样的:

var ss = SpreadsheetApp.getActive(); 
var sheet = SpreadsheetApp.getActiveSheet();
var formUrl = ss.getFormUrl(); // Use a form attached to sheet 
var form = FormApp.openByUrl(formUrl); 
var items = form.getItems();
var cell_content = "Some string value in the spreadhseet"; 
 for (var i = 0; i < items.length; i++ ) {    
       var id_item = items[i].getId();
       var type_item = items[i].getType();
var item_of_form = form.getItemById(id_item);
if (type_item == "MULTIPLE_CHOICE"){
          formItem = item_of_form.asMultipleChoiceItem(); 
          if (formItem.hasOtherOption()){
            formItem.showOtherOption(true);                                   
          }
          var response = formItem.createResponse([cell_content]);
          formResponse.withItemResponse(response);    
     }
var url = formResponse.toPrefilledUrl();
Logger.log(url); 

一切正常(使用文本和段落响应,甚至使用复选框和多项选择(除了其可选值)。

如何将复选框和多项选择的可选值放入预填表单中?

似乎没有办法直接声明您要将响应设置为 "other"。但是,您可以手动完成,它显示了预填充 URL 是如何制作的。我写了一些代码(如下),它将获取 sheet(范围 B2:B4)中的项目列表,这些项目应该是预先填写在“other.

”中的响应

URL 将被记录,但您可以随意使用它们。另外,请记住,这仅适用于 "other" 问题,您获取数据的列表将预先填充 "other",无论它说什么。

试试下面的代码:

function myFunction() {
  var ss = SpreadsheetApp.getActive();

  var formUrl = ss.getFormUrl(); // Use a form attached to sheet 
  var form = FormApp.openByUrl(formUrl); 
  var items = form.getItems();
  var formItem = items[0].asMultipleChoiceItem(); // The question 

  var id = formItem.getId().toString()
  var otherResponse = ss.getRange("B2:B4").getValues();

  for (var i = 0; i < otherResponse.length; i++){
    var string = "__other_option__&entry." + id + ".other_option_response=" + otherResponse[i];
    var other = formItem.createResponse(string);

    var respWithOther = decodeURIComponent(form.createResponse().withItemResponse(other).toPrefilledUrl());
    var firstId = respWithOther.substring(117, 127);

    var finalUrl = respWithOther.substring(0, 151) + firstId + respWithOther.substring(161, respWithOther.length);
    Logger.log(finalUrl);
  }
}