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 912
5 REPLIES 5

I don't know about the errors you are getting and I'm afraid it might be outside the scope of this forum.

But as a side note, since you are already using AppSheet, why don't you handle everything you describe through AppSheet instead of separate scripts running on your sheet? It is worth it, and you wouldn't need any scripting. 

Hi @Joseph_Seddik 

Thank you for your answer.

Well some of the reason why I dont do it in appsheet might be because I am pretty new, so I am actually not sure how I could do the same.

When the answers go to my Google sheet, I have 3 spreadsheets there.

1. All raw data from Appsheet is coming here without any manipulation.

2. Next spreadsheet shows relevant data I take from the first sheet and also adds different 'valid until' hours depending on different scenarios, and creates a PDF file which then is the Parking permit that autoprints to the drivers.

3. The last sheet is actually showing the same as the second sheet, the difference is that this sheet only shows registrations within the last 48 hours (See this screenshot: https://prnt.sc/HaoC2fhUKyut) - the sheet is cleaned up and new registrations are added automatically, it is important for me that no-one has to refresh the page ๐Ÿ™‚

That 'Last48Hours' sheet is showing in an office on a big TV so everyone easily can see who has registered.

I am not sure how I could show this with appsheet?

All what you have described is perfectly possible and even easier with AppSheet, and you'd need even less tables (sheets). 

Start here: 

App design 101 - AppSheet Help

 

Thanks,

When I have the time, I will see if I can manage to do it in Appsheet.
Thanks again

Hi Joseph_seddik,

Sorry for late reply, I haven't had the time. But now I do, better late than never ๐Ÿ™‚

And wow, yes, you were so right. I think I have managed to do almost the same with the Appsheet as all of these stupid script does, amazing ๐Ÿ™‚

I still have one question though.

The script running in Google sheet (appscript) is creating a pdf file with relevant data from the appsheet form and saves this PDF in my dropbox account. (I save it do dropbox because there is instant sync on the dropbox app installed on a windows tablet) - If I save the same PDF file to Google Drive, it can take up to 15-30 seconds before sync to G-drive on the Windows tablet. 

The reason why I am syncing the PDF file to the tablet, is because I am running 'FolderMill' software to watch a folder (The dropbox folder with the PDF file) to autoprint the file. This way the drivers can easily print their own Parking Permit and it autoprints.

So my question:
I would still have to call a script, e.g the dropbox script to sync the PDF file made by Appsheet, to save it to dropbox, and still use foldermill to autoprint, right?

There is no way I can autoprint the PDF file made by Appsheet, from within appsheet, right?
If that's the case, it is also more than okay. Already now I am happy to get rid of all the scripts.
I can live with one script to save the PDF file to dropbox ๐Ÿ™‚

All the best,

Top Labels in this Space