add item in google form

18 views
Skip to first unread message

cru...@itcgoriani.istruzioneer.it

unread,
Jan 16, 2022, 3:09:28 PMJan 16
to Google Apps Script Community
Hello everyone,
In a Google form ,that contains already 3 questions, I have to add a question before the first one after the third answer.
I have written the script that runs after each answer, but how can I choose where to add the question?
This is the code that I write:

var NumAnswer = 2; 

function onOpen() {
  var ui = FormApp.getUi();
  ui.createAddonMenu().addItem('Set Trigger', 'SetTrigger').addToUi();
}

function AddQuestion() {
  var form = FormApp.getActiveForm();
 
  var responses = form.getResponses();
 
  if (!responses) {
    return; 
  }
  if (responses.length > (NumAnswer -1)) {
    
    'ADD CODE
    '........
    '.........

  }
  
}
function SetTrigger() {
  
  
  var props = PropertiesService.getScriptProperties();
  if (props.getProperty('existstrigger')) {
    return;  
  }
      
  var triggers = ScriptApp.getProjectTriggers();
  if (triggers.length > 0) {
    for (i = 0; i < triggers.length; i ++) {
      if (triggers[i].getHandlerFunction() == 'addQuestion') {
        props.setProperty('existstrigger', true);
      }
    }
  }
  
  if (triggers.length == 0 || !(props.getProperty('existstrigger'))) {
    ScriptApp.newTrigger('addQuestion')
    .forForm(FormApp.getActiveForm())
    .onFormSubmit()
    .create();
    props.setProperty('existstrigger', true);
  }
}

thanks!

Clark Lind

unread,
Jan 17, 2022, 9:29:10 AMJan 17
to Google Apps Script Community
To be sure I understand correctly, you want to insert a 4th question, at the beginning of the form, after three people have submitted the form? You want a 4th question for the 4th person put at the beginning of the form?

If the above is true, I think you can simply use the form.moveItem() method. Something like this (untested) should do the job:
function AddQuestion() {
  var form = FormApp.getActiveForm();
 
  var responses = form.getResponses();
  
  if (!responses) {
    return; 
  }
  if (responses.length > (NumAnswer -1)) {
      //var newQuestion = your code to create a new question; example:
      var newQuestion = form.addTextItem();
        newQuestion.setTitle('What is your name?');
    //get the itemId of your new question
      var newQuestionId = newQuestion.getId();
    //move the new question to the first index of all items
      form.moveItem(newQuestionId, 0);
  }
}
Reply all
Reply to author
Forward
0 new messages