Search code examples
google-apps-scriptgmail-addons

Add sections dynamically to card


I'm new on Apps Script and I'm a bit lost, is there a way to add dynamically a section on a card? I'm trying this:

  var card = CardService.newCardBuilder()
      .setHeader(peekHeader)
      .addSection(section).build();

  card.addSection(sectionTo);

And I'm getting TypeError: card.addSection is not a function

If I try:

  var card = CardService.newCardBuilder()
      .setHeader(peekHeader)
      .addSection(section);

  card.addSection(sectionTo).build();

I get another error:

The value returned from Apps Script has a type that cannot be used by the add-ons platform. Also make sure to call build on any builder before returning it. Value: values {
  struct_value {
  }
}

Update:

Sections are defined like:

  var section = CardService.newCardSection()
                  .addWidget(CardService.newTextParagraph().setText("The email is from: " + from));
  var sectionTo = CardService.newCardSection()
                  .addWidget(CardService.newTextParagraph().setText("To: " + to));

Solution

  • Once a card has been built, unfortunately it cannot be modified anymore.

    If e.g. on an event you want to change the card content - you need to build and return a new card that would replace the old one.

    The correct way to build the card would be

      var card = CardService.newCardBuilder() 
      .setHeader(peekHeader)
      .addSection(section)
      .addSection(sectionTo)//; // or using section card.addSection(sectionTo); // or using section 
      .build();
    

    If instead you try to apply

    card.addSection(sectionTo).build();
    

    to

     var card = CardService.newCardBuilder()
          .setHeader(peekHeader)
          .addSection(section);
    

    the variable card will represent a section - and adding a section to a section will give you an error.