Fragosojp
Fragosojp

Reputation: 151

How to generate an "id" on WEB google App Script?

I have this script to insert data into the spreadsheet.

I created a way to generate an ID with the value of the date and time, the problem that is too large

example: E1567301439829

Is there any way I can generate a unique and short ID for each record?

I would like to leave an id like: E001, E002, E003....

Link Ws: https://docs.google.com/spreadsheets/d/1OokFvWCx-ROkhaLP1nYQPDAu8zgCTeizHHq0ABnBL0A/edit#gid=0

 function doGet(e){
  Logger.log(e.parameter);
  return HtmlService.createHtmlOutputFromFile("index");
  
}

function registrar(name){
  var url = "https://docs.google.com/spreadsheets/d/1OokFvWCx-ROkhaLP1nYQPDAu8zgCTeizHHq0ABnBL0A/edit#gid=0"
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName("Página1");
  
  
  var date = new Date().valueOf();
  var idEntrada = 'E' + date
  
  ws.appendRow([idEntrada,name]);
  
}
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    
    
    <label>Nome</label><input type="text" id="nome">
    
    <button id="btn">Registrar</button>
    
    <script>
    
    document.getElementById("btn").addEventListener("click",salvar);
    
    function salvar(){
    
       var campoNome = document.getElementById("nome").value;
       
       google.script.run.registrar(campoNome);
       
       document.getElementById("nome").value = "";
    }
    
    
    </script>
    
  </body>
</html>

Upvotes: 1

Views: 790

Answers (1)

Tanaike
Tanaike

Reputation: 201358

How about this answer? Please think of this as just one of several answers.

Pattern 1:

If each row is appended using appendRow(), how about this modification?

From:

var date = new Date().valueOf();
var idEntrada = 'E' + date

To:

var idEntrada = 'E' + ('00' + ws.getLastRow()).slice(-3);

Pattern 2:

If there are several empty rows, how about this modification?

From:

var date = new Date().valueOf();
var idEntrada = 'E' + date

To:

var idEntrada = 'E' + ('00' + (ws.getRange("A2:A").getValues().filter(String).length + 1)).slice(-3);

Note:

  • In your script, it seems that you are using Web Apps. In this case, when you modified your script, please redeploy Web Apps as new version. By this, the latest script is reflected to Web Apps. If you are using Web Apps as the developer mode, this can be ignored.

References:

If I misunderstood your question and this wat not the direction you want, I apologize.

Upvotes: 2

Related Questions