Function that triggers when specific rows are empty or null

Hello there,

Is there a way to create a trigger function that will delete a row from a table completely if some field(s) are null or empty?

If so, can someone please explain to me and guide me how to do it.

Thank you very much.

Hi Diogo,

You described a condition for deletion (when some field(s) are null or empty). That is clear. However, what should actually trigger the function? Is it when a record is created in the database? Or updated? Or perhaps when a user logs in or does something?

Regards,
Mark

Hello Mark.

Thank you for the response.

It should be when a record is updated. Could you help me please?

Thank you!

Hi @Diogo_Potes,

are you using JavaScript or Codeless?

Hi @stanislaw.grin ,

I’m developing a website in JS so i’m confortable with js but i haven’t started to create the function or how to even start. Don’t know which would be easier. I don’t know if i’m explaining well.

Thank you.

I highly recommend to start from this documentation:
https://backendless.com/docs/bl-js/bl_event_handlers.html

  1. Go to the Cloud Code section
  2. Open the Handlers menu
  3. Click New Event Handler
  4. Create a handler

Here is a doc part about how to stop event processing (let’s say a user wants to update some records in the MyTable table, before this record will be saved, you validate the incoming object (req.item) in this handler and if you don’t want the object to be saved, return { short: true }:

Backendless.ServerCode.User.beforeRegister(async req => {
  // your validation logic goes here

  // return a special JS object with the "short" property set to true
  return { short: true }
})

https://backendless.com/docs/bl-js/bl_short_circuit.html

Or you may create an afterUpdate handler instead of beforeUpdate, and remove the object from DB in case it didn’t pass your validation logic.

Hope it helps.

Regards,
Stanislaw

So, if i wanted to create the logic: if two fields are null, then remove record from DB would be something like this ? :

Backendless.ServerCode.Persistence.afterUpdate('UserMovie', async function(req, res) {
  //add your code here
  if(req.item.Position == null && req.item.Rating == null) {
    
    Backendless.Data.of('UserMovie').remove(req.item)
    
  }
});

Or is it wrong? I’m testing and i’m seeing that if i only change field Position to null, the record is deleted right away, even if field Rating is not null.

Thank you.

The code looks ok, but you need to put await before Backendless.Data.of('UserMovie').remove(req.item) for the event handler to be correctly finished.
Regarding your issue, I suggest using logs in your code to debug and see what’s happening. Maybe some property is written with a typo and thus its value is == null.
Let me know about the results.

1 Like

I got it working by altering instead of req.item => res.result.

Thank you very much!