grreeenn
grreeenn

Reputation: 2545

Apps script: use a form as a template for other forms creation

I have a form with a set of questions, and I want to use it for other forms creation. In other words, I want to iterate through this template form items, choose those that I need and append them to another, newly created form.

I had no problem with getting the items and choosing those that I need; however, I can't find the way to append these items to another form - all of the Form.addSomethingItem() methods don't take arguments (docs for example). Is it really impossible, or do I miss something foolishly simple?

Upvotes: 1

Views: 330

Answers (2)

TheMaster
TheMaster

Reputation: 50445

There are two ways to achieve this:

  1. Make a copy of the form using DriveApp and remove/modify items in-place on the new form copy.

  2. Iterate over existing items, check it's type and add them to the new form. For example, The following gets Item1's enum and converts it to a camelCase string and executes add{Type}Item method, where Type is MultipleChoice in case of MULTIPLE_CHOICE Enum Item type.

const newForm2Item0 = Form2[
  `add${String(Form1.getItems()[0].getType())
    .toLowerCase()
    .replace(/(^|_)[A-Z]/gi, match =>
      match.toUpperCase().replace('_', '')
    )}Item`
]();//equivalent to Form2.addMultipleChoiceItem()

You would then add choices and other configurations as needed in a similar manner.

Upvotes: 3

RayGun
RayGun

Reputation: 491

Form methods like addTextItem() don't take arguments, rather they return Items classes (e.g. TextItem). Those Item classes have their own methods for assigning properties to a question on a form.

Examples

here's an example of adding a text item with a specific title

form.addTextItem().setTitle('I am a text question title');

here's an example of adding a multiple choice item to a form with some choices

var item = form.addMultipleChoiceItem();
var choices = ['choice 1', 'choice 2', 'choice 3'];
choices.forEach(function(choice) {
  item.createChoice(choice);
})

Upvotes: 1

Related Questions