Modify existing form Values - GetChoices() not working

爷,独闯天下 提交于 2020-02-24 16:16:47

问题


Why does '.getChoices()' not work for existing list items?

I have the following code which gets an item in a form by it's ID, and I intend to update the values of the form item. However, when using the .getChoices() method, it fails with the error 'TypeError: Cannot find function getChoices in object Item.'

The item I'm fetching is a list item as required, and when a list item is created then fetched, it works normally as in the sample code listed here.

My code is as follows:

function getWeekNumberFormItem() {
   var form = FormApp.getActiveForm();
   var item = form.getItemById(12345);//redacted for privacy, but the ID in here is correct. 
   var title = item.getTitle();
   var itemType = item.getType();
   Logger.log('Item Type: ' + itemType);
   Logger.log('Item Title: ' + title);
   var choices = item.getChoices();
   Logger.log(choices);
}

and to prove it is a list item, my logging output is:

Am I using this incorrectly, or can this only be used when Apps script creates the item also? How instead would I get the choices in this list item and update them with new options? I see other users have managed to do this, so I believe it's possible.


回答1:


Item is an interface class that provides a few methods applicable to all form items. "Interface objects are rarely useful on their own; instead, you usually want to call a method like Element.asParagraph() to cast the object back to a precise class." ref

Since .getChoices() is a method that belongs to the ListItem class, and does not appear in Item, you need to cast your Item to ListItem using Item.asListItem().

...
var itemType = item.getType();

if (itemType == FormApp.ItemType.LIST) {

  var choices = item.asListItem().getChoices();
  //                 ^^^^^^^^^^^^
}
else throw new Error( "Item is not a List." );


来源:https://stackoverflow.com/questions/30359367/modify-existing-form-values-getchoices-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!