问题
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