Search code examples
google-cloud-sqlgoogle-app-maker

How to use database data on Event OnBeforeCreate


I want to get the last data created on my database, more specifically the field called: "Saldo Atual" and after this get the form data field "Valor" and make a sum between this fields (the Old one "Saldo Atual" and the new "Valor") before create a new record and add this "Valor" and the sum of "Saldo Atual"+"Valor".

I don't know how to get the database last record

var saldoAtual = 

record.saldoAtual = saldoAtual + record.valor;

And I want to know if the second line it's correct to save the sum of "Saldo Atual"+"Valor"


Solution

  • Based on my comment, I think that your records will need to have a Date_Created field. Then in your onBeforeCreate event the following script should work (this is untested, so you need to do your own testing):

    var query = app.models.YourModelTheSameAsYourEventModel.newQuery();
    query.sorting.Date_Created._descending();
    query.limit = 1;
    var lastrecord = query.run();
    
    record.saldoAtual = lastrecord.saldoAtual + record.valor; //You may need to use lastrecord[0].saldoAtual
    
    record.Created_Date = new Date();
    

    Try that and do some testing to see if this yields your desired output.