Script is triggered several times when it shouldn't

Hi, 
I have actually orginally posted the below text here:
https://support.google.com/docs/thread/225184819/script-is-triggered-several-times-when-it-shouldn-t...

But I was wondering if someone from here know if there is another way of triggering scripts in google sheet coming from Appsheet other than 'OnChange'? 

If you read below text, I dont know if my problem could be solved with better code, but as I dont know much about scripting ( and used ChatGPT a lot) I think my problem could be solved if I could just use the evet type 'On formsubmit'?





Hi all, 


For the last 3 months this has been running okay, but today a problem started.

Story short:

I am running an Appsheet app on a tablet in a public place where truck drivers can enter information and get a parking permit printed.

Their answers from the app goes into a Google spreadsheet.
In google sheet I have 4 different scripts running to handle the answers.

Normally if I had to do some changes in the sheet, I deleted my 'Trigger' to be able to do adjustments without triggering the script.

Before the appsheet app, I was using Google Form, and the trigger event type was set to 'On form submit', it worked brilliant.

For reasons, I changed to use Appsheet, which means my trigger event is now set to 'On change', so each time a truck driver is filling out the info on the tablet, his answer goes to the google sheet, and script is triggered because of a 'change'.

In the beginning I couldn't understand that each time I would do a small adjustment fx making a cell a bit bigger or smaller, or maybe put a title in the top of the sheet, you know just any adjustments in the sheet, then the script was triggered and processed the last row again, giving me a duplicate row.
Yay I figured out, oooh yeah it's because the trigger is 'on change'. Damn I hate that appsheet cannot use the event 'On form submit'.

But yes, since I now know that I just have to delete my trigger, do the adjustments and then enable (or create) the trigger again, then it runs.


But here is the problem.
From today, it starts duplicating all the anwers, the same way as if I was doing some adjustments and therefor triggered the script again, but no-one is touching the sheet. It is locked and people only have read-permissions.

If I go to the executions log, each time a new entry comes in it is handled correctly, but one second later, it is triggered again with this error:

Jul 11, 2023, 2:12:59โ€ฏPM
Error
TypeError: Cannot read properties of undefined (reading '0')
    at copyDataToFilter(copyDataToFilter:78:42)



If a new driver enters info for a parking permit, it is handled correctly, but a second later, the log shows error again, it can then be this error:

Jul 11, 2023, 2:09:22โ€ฏPM
Error
TypeError: Cannot read properties of undefined (reading '0')
    at updateLast48Hours(updateLast48Hours:38:25)
    at saveToDropbox(createDoc:141:3)
    at createDoc(createDoc:87:3)
    at dataForDoc(createDoc:25:3)
    at copyDataToFilter(copyDataToFilter:97:3)


It continues like this all day long with these two above errors.
The problem is, that the sheet our office uses to get an overview of which trucks are registered, they are now duplicated, and actually sometimes 3 times.
Like mentioned in the beginning, I have 4 scripts running, but I guess this is the one that is the problem, right?


// Copy all columns from range B2 to H from 'Responses' sheet, and insert into 'Filter' sheet only in column B to G
// A trigger is created in App Script menu under 'Triggers' to start the below script each time a new form-respons is submitted.

function copyDataToFilter(e) {
  var sourceSheet = e.source;
 
  // Get sheet "Responses"
  var sourceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Responses");

  // Get sheet "Filter"
  var targetSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Filter");

  // If sheet doesn't exist, create it
  if (targetSheet == null) {
    targetSheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet("Filter");
  }

  // Get data from "Responses" sheet
  var range = sourceSheet.getRange("B2:G");
  var values = range.getValues();

  // Get last row number in target sheet
  var lastRow = targetSheet.getLastRow();

  // Process data and store result in a new array
  var result = [];
  for (var i = 0; i < values.length; i++) {
    var row = values[i];
    if (row[0] == "") {
      continue;
    }

    // Add row to the result array with current timestamp row[1] = Language column, row [2] = Truck column etc.
    var newRow = [new Date(), row[1], row[2], row[4], row[5], row[6]];
    result.push(newRow);
  }

  // Insert data from result array into Filter sheet starting from next row after the last row
if (result.length > 0) {
  var newRowIndex = lastRow + 1;
  var newValues = result[result.length - 1];
  targetSheet.getRange(newRowIndex, 1, 1, newValues.length).setValues([newValues]);
}


  // Set numberformat of column A to 'Day, Month, Year Hour & minute'
  targetSheet.getRange(lastRow + 1, 1, result.length, 1).setNumberFormat("dd. MMM yyyy HH:mm");

  // Set format in column B, C to text and numbers
  targetSheet.getRange(lastRow + 1, 2, result.length, 2).setNumberFormat("@");

  // Set numberformat of column D and E to "HH:mm"
  targetSheet.getRange(lastRow + 1, 4, result.length, 2).setNumberFormat("HH:mm");

  // Align data in column A to the left
  targetSheet.getRange(lastRow + 1, 1, result.length, 1).setHorizontalAlignment("Left");

  // Center all data in column B to F
  targetSheet.getRange(lastRow + 1, 2, result.length, 5).setHorizontalAlignment("Center");

//------------------------------------------------------------------------------------------------//


// This will add hours to the 'Valid Until' field
// It adds 48 hours on Fridays from 17:30 to Saturday morning 08:00
// All other days 24 hours is added

// Get active sheet
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Filter");

// Get range of data
var data = sheet.getDataRange().getValues();
var lastRow = sheet.getLastRow();
var startRow = lastRow-1; // Only process the last row

// Loop through the range and set date & time format
for (var i = startRow; i < lastRow; i++) {
  var originalDateTime = new Date(data[i][0]);
  var day = Utilities.formatDate(originalDateTime, "Europe/Copenhagen", "EEEE");
  var hour = originalDateTime.getHours();
  var minute = originalDateTime.getMinutes();

  // Check if day is Friday 22:30 to Saturday 08:00 and add 48 hours, else add 24 hours
  if (day === "Friday" && (hour > 22 || (hour === 22 && minute >= 30)) || day === "Saturday" && hour < ๐Ÿ˜Ž {
    originalDateTime.setTime(originalDateTime.getTime() + 2*24*60*60*1000); // adding 2 days
  } else {
    originalDateTime.setTime(originalDateTime.getTime() + 24*60*60*1000); // adding 1 day
  }
  sheet.getRange(i+1, 6).setValue(originalDateTime);
  sheet.getRange(i+1, 6).setNumberFormat("dd. MMM yyyy HH:mm");
  sheet.getRange(i+1, 6).setHorizontalAlignment("Center");
}



  // Call dataForDoc function after copying data is complete
  dataForDoc();

}
 


I have used chapGPT a lot to create all 4 scripts, and right now it is not for any help, so I am hoping one you know how I can prevent this from happening.
0 5 2,901
5 REPLIES 5
Top Labels in this Space