user2262933
user2262933

Reputation: 81

Check to see if a Google form has a destination spreadsheet

I am trying to use Google apps script to get information from a form, but I am thinking that it is a good Idea to check and see if the form already has a destination spreadsheet attached to it. If it does I want to grab the ID if it does not I want to create one. Every time I run the code below The de-bugger throws an error telling me "The form currently has no response destination."

Please help

    var form = FormApp.getActiveForm();
    var formName = form.getTitle();


    function randomQuestion() {
      var theFormID = form.getId();

      var sheetID = function sheetID() {

      if ( form.getDestinationId() === 'undefined' ) {
          var ss = SpreadsheetApp.create(formName + ' (Responses)');
          form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
          return form.getDestinationId();

      }else {
       return form.getDestinationId();}

      }
    var sheet = sheetID();
    g;  // <-un-comment this to make the de-bugger throw an error =)
    }

Upvotes: 3

Views: 1785

Answers (2)

user2262933
user2262933

Reputation: 81

Here is the Code that I used to test if there is a Response Spreadsheet and if not create one.

    var form = FormApp.getActiveForm();
    var formName = form.getTitle();
    var ssID;

    try {
      ssID = form.getDestinationId();
    }
    catch(e) {
      var exception = e.name;
      if (exception === "Exception" ){
        var ss = SpreadsheetApp.create(formName + ' (Responses)');
        form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());
        ssID = form.getDestinationId();
      }else{
        ssID = form.getDestinationId();
      }
    }

Upvotes: 3

wchiquito
wchiquito

Reputation: 16551

The method getDestinationId() throws an exception when the form has no response destination. You need to handle this with a try...catch, something like:

...
var form = FormApp.getActiveForm(), idResponse;
try {
  idResponse = form.getDestinationId();
}
catch(e) {
  // TODO
}
...

Upvotes: 2

Related Questions