Home > Enterprise >  How can I disable duplicating data
How can I disable duplicating data

Time:10-19

I have an html form which I'm passing data to and taking the values here. I want to create a system to catch whenever the same data is repeated. I'm doing the if statement below which is supposed to catch whenever the same data is entered, but it is not working properly. The issue is writes the same data multiple times.

function processFormClients(formObject) {
  var url = "LINK";
  var ss = SpreadsheetApp.openByUrl(url);
  var Clients = ss.getSheetByName("Clients");

  var data = Clients.getDataRange().getValues();
  for (var i = 0; i < data.length; i  ) {
    
    if(data[i][1] !== formObject.client_name) {
      Clients.appendRow([
        Math.floor(Math.random() * Date.now()),
        formObject.client_name,
        formObject.client_company,
        formObject.client_budget,
      ]);
    } else if (data[i][1] === formObject.client_name) {
      console.log('failed')
    }
}
 

CodePudding user response:

Modification points:

  • In your script, when the column "B" of var data = Clients.getDataRange().getValues() is not same with the value of formObject.client_name, Clients.appendRow is run every time. Only when the value of formObject.client_name is the same with data[i][1], console.log('failed') is run. I thought that this might be the reason of your issue.

In order to append the data of [Math.floor(Math.random() * Date.now()), formObject.client_name, formObject.client_company, formObject.client_budget] when formObject.client_name is not existing in the column "B", how about the following modified script?

Modified script:

function processFormClients(formObject) {
  var url = "LINK";
  var ss = SpreadsheetApp.openByUrl(url);
  var Clients = ss.getSheetByName("Clients");
  var search = Clients.getRange("B1:B"   Clients.getLastRow()).createTextFinder(formObject.client_name).findNext();
  if (search) {
    console.log('failed');
    return;
  }
  Clients.appendRow([
    Math.floor(Math.random() * Date.now()),
    formObject.client_name,
    formObject.client_company,
    formObject.client_budget,
  ]);
}
  • In this modification, the duplicated value of column "B" is checked using TextFinder. When TextFinder is used, the process cost can be reduced a little. Ref
  • When this script is run, only when formObject.client_name is not existing in the column "B" of the sheet "Clients", Clients.appendRow is run.

References:

  • Related