EN VI

Google-apps-script - Form not found, but ID and name are correct?

2024-03-16 10:30:05
How to Google-apps-script - Form not found, but ID and name are correct?

I a google form with the correct form ID and name added to this apps script:

enter image description here

    function openForm() {
      var form = findFormByName('Comments');
      if (form) {
        populateQuestions(form);
      } else { 
        Logger.log('Form not found');
      }
    }

    function findFormByName(formName) {
      var forms = FormApp.openById('1s0rjQIRY2i8CZsoxlu--TBR7q4b3wHxBslItWOMrc1s').getItems(FormApp.ItemType.FORM);
      for (var i = 0; i < forms.length; i++) {
        var form = forms[i].asForm();
        if (form.getTitle() === formName) {
          return form;
        }
      }
      return null;
    }

    function populateQuestions(form) {
      var googleSheetsQuestions = getQuestionValues();
      var itemsArray = form.getItems(FormApp.ItemType.LIST);

      if (googleSheetsQuestions.length > 0) {
        var choiceArrayA = removeDuplicates(googleSheetsQuestions.map(function(row) {
          return row[0] ? String(row[0]).trim() : '';
        }));
        if (itemsArray.length > 0) {
          var question1 = itemsArray[0].asListItem();
          question1.setChoiceValues(choiceArrayA);
        }
      }
    }

    function removeDuplicates(array) {
      return array.filter((value, index, self) => self.indexOf(value) === index);
    }

    function getQuestionValues() {
      var ss = SpreadsheetApp.openById('1OK0EIoGRD8RdQ4gOeCqy6ycT5Y-MvLZYXBvQo2MpJpI');
      var questionSheet = ss.getSheetByName('Raw Data');
      var returnData = questionSheet.getRange(2, 1, questionSheet.getLastRow() - 1, 2).getValues();
      return returnData;
    }

any clue what im doing wrong? I added in the rest of the code pertaining to the other functions the first two blocks of code are referencing.

edit: picture to show me implementing a solution to no avail.

enter image description here

Solution:

Getting Form Title

What's happening with your code is that you are trying to get the Question type and compare it with your supposed Form Title. I created a fix with your form title part of code.

Sample Code:

function openForm() {
  var form = findFormByName('Comments');
   if (form) { populateQuestions(form); }
  else { Logger.log(form); }
}

function findFormByName(formName) {
  var forms = FormApp.openById('1B6gBnmAcxvRo-KYtLQOqPgOWaphXNDJ-YWHyqVh893k');
  var formTitle = forms.getTitle();
  
  if (formTitle === formName) {
    return forms;
  }
  else {
    return null
  }
}

Reference:

getTitle()

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login