Add sections dynamically to card

Viewed 584

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));
2 Answers

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.

As @ziganotschka was saying, after building a card, this card cannot be modified. When you do CardService.newCardBuilder(), you are creating an object with type CardBuilder, but when you do built(), return object was type Card, so you cannot longer do .addSection over my object card (with type Card).

On the second code, addSection is properly done, but since return object from .build() is not save anywhere and after that I'm returning card object (still type CardBuilder), it is causing the second error. That's why, now I get it:

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.
Related