0
votes

As I would like to create documents by merging the entries in a list into a Google Docs template. I have therefore integrated the DocumentMerge method from my previous question into a printButton in a list widget.

enter image description here

Clicking on the printButton should produce a document that merges the contents of the current row into the document template. But when I click on the printButton the method fails due to a circular reference. How can I fix that? The print method goes like this ...

 function printReview(widget) { 
  var review = app.models.Review.getRecord(widget.datasource.item._key);

  var templateId = 'templateId';
  var filename = 'Review for ...' + new Date();

  var copyFile = DriveApp.getFileById(templateId).makeCopy(filename);

  var copyDoc = DocumentApp.openById(copyFile.getId());
  var copyBody = copyDoc.getBody();
  var fields = app.metadata.models.Review.fields;

  for (var i in fields) {
    var text = '$$' + fields[i].name + '$$';
    var data = review[fields[i].name];
    copyBody.replaceText(text, data);
  }

  copyDoc.saveAndClose();
}
1
From what I deduce, you are passing the widget object to the server script and that is why you are getting that circular reference. Ideally, you should have a client script that gets the item key and then calls the server script using google.script.run passing only the item key and not the widget object. - Morfinismo
Unfortunately, I am not familiar with the handover of the item key to a server script. How would that look like? - Johan W.

1 Answers

2
votes

As Morfinismo noticed you are getting the error because you are trying to pass complex object from client to server and serializer fails to handle it. In order to fix that you need to adjust your code:

// onClick button's event handler (client script)
function onPrintClick(button) {
  var reviewKey = button.datasource.item._key;

  google.script.run
    .withSuccessHandler(function() { /* TODO */ })
    .withFailureHandler(function() { /* TODO */ })
    .printReview(reviewKey);
}

// server script
function printReview(reviewKey) {
  var review = app.models.Review.getRecord(reviewKey);
  ...
}