qurquru
qurquru

Reputation: 198

Get list of all Sections in Google Form or get that property from each response?

TL;DR: How do i get the Section title that each response belongs to?

Context: My friend sends out a Google Form to their clients each week. It's basically a food menu that the client has to choose from to make an order and i made a parser for it.

The problem is that the food options in the menu are the same for every day of the week so i split the Google Form into Sections for each day. To work with Responses in Google Sheets i'm going to parse them into the table that's going to look something like this:

USERNAME | DAY OF THE WEEK | QUESTION | RESPONSE
USERNAME | DAY OF THE WEEK | QUESTION | RESPONSE
USERNAME | DAY OF THE WEEK | QUESTION | RESPONSE
USERNAME | DAY OF THE WEEK | QUESTION | RESPONSE

My issue is that after looking through Google's Documentation i wasn't able to find a method that returns a section name that each response belongs to. Is splitting forms into Sections the best idea in my case? If so how do i achieve my goal?

Upvotes: 1

Views: 1448

Answers (2)

Chrostip Schaejn
Chrostip Schaejn

Reputation: 3107

To get only all section titles and descriptions, you can use this:

function myFunction() {
  let form = FormApp.getActiveForm();
  let sections = getSections(form);
  
  sections.forEach((section) => {
    Logger.log(section.getTitle());
    Logger.log(section.getHelpText());
    Logger.log(section.getIndex());
  });
}

function getSections(form) {
  let sections = [];
  let items = form.getItems();
  items.forEach((item) => {
    let type = item.getType();
    if (type === FormApp.ItemType.PAGE_BREAK) {
      sections.push(item);
    }
  });
  return sections;
}

Upvotes: 0

Boris Baublys
Boris Baublys

Reputation: 1203

Indeed, in the documentation, I also did not find an opportunity to get the title of the section by the itemId or itemIndex. I had to write the code myself. I checked it on this form - it works well.

Note. closestLeft - find the nearest lower index.

Try this:

function myFunction() {
  var form = FormApp.getActiveForm();
  var items = form.getItems();
  var sectionIdxs = [];
  for (var i = 0; i < items.length;i++){
    var item = items[i];
    var itemType = item.getType();
    var itemIdx = item.getIndex();

    if (itemType == "PAGE_BREAK") {
      sectionIdxs.push(itemIdx);
    }

    var closestLeft = Math.max(...sectionIdxs.filter(v => v < itemIdx));
    if (closestLeft == "-Infinity"){
      var section = 1;
    } else {
      section = closestLeft;
    }
    if (itemType != "PAGE_BREAK"){
      var sec = sectionIdxs.indexOf(section) + 2;

//      Shows the name of the section
      Logger.log("typeItem" + i + ": " + itemType + ", itemTitle: " + item.getTitle() + ", itemId: " + item.getId() + ", itemIdx: " + itemIdx + ", Section: " + sec);
    }
  }
}

Upvotes: 1

Related Questions