Matthew
Matthew

Reputation: 379

Changing orders of items in Google Form with Google App Script

I am trying to programmatically create Google Forms with data from Google SpreadSheet, based on a template Google Form.

Is there anyway to change the order of the items? Occasionally we need to use the "duplicate" function on items, but then the duplicated item is appended at the end of the form, which is not what we want.

Thanks a lot in advance!

Upvotes: 0

Views: 1313

Answers (2)

Jason Bagley
Jason Bagley

Reputation: 11

There's a known issue with this method. It fails to work on the variable of the duplicated objects created by scripts, likely because the item will be initialized as a specific item type instead of a generic item (e.g. it is a list item instead of an 'item').

https://issuetracker.google.com/issues/175979141?pli=1

You can fix this by using a workaround, such as this:

form.moveItem(form.getItemById(newItem.getId()), desiredIndex);

Upvotes: 0

tehhowch
tehhowch

Reputation: 9862

By definition, the duplicate() methods append to the end e.g. CheckboxItem#duplicate().

After you create an item, you can order it as you wish, for example:

function duplicateAndMove(form, toDuplicate) {
  var newItem = toDuplicate.duplicate();
  var desiredIndex = toDuplicate.getIndex() + 1;
  if (desiredIndex !== newItem.getIndex()) {
    form.moveItem(newItem, desiredIndex);
  }
  // Allow chaining on the new item.
  return newItem;
}

See the Apps Script Form Service documentation for more details: https://developers.google.com/apps-script/reference/forms/

Upvotes: 6

Related Questions