How to Automatically Record a User ID when Servoy Inserts a new record.

How to automatically update a field when new records are Inserted.

So, you want field [user_id] to be set to the current user whenever Servoy inserts a new record to table [customers]. And you don’t want to manually set the field everywhere you use the table.

One easy way is to create an afterRecordInsert event for the table.

And here is how I achieved it.

How to create an afterRecordInsert event for the Solution:

  1. Select the Database Server to use.
  2. Double click the table to use on that Database Server.
  3. Select the Events tab.
  4. Choose the name of the Solution to add the event to. In the picture, I’m using a Solution called ‘ExampleSolution’.
  5. Double click -none- on the afterRecordInsert row of the events list.

Select Method:

  1. You want to create a new method, so click the Entity button.

Specify a method name:

  1. Servoy will suggest afterRecordInsert as a name for your new method. Accept this default name by clicking the Create private button.

Open the created Method in the editor:

  1. Servoy will create a default stub of your new method ready for you to edit, press the OK & Show button to start editing it.

Replace the Servoy generated stub code in our new event:

Below is example code to place in the Servoy generated stub.

The code assumes you have a function in globals called getUserId() that will return the user’s ID number. Please adapt it for your own needs, etc.

function afterRecordInsert(record) {
    application.output("{afterRecordInsert} " + record);
	
    try {
        record.foundset.setDataProviderValue('user_id', globals.getUserId());
    } catch(e) { 
        application.output(e.message + '\n' + e.stack, LOGGINGLEVEL.ERROR); 
    }
}

A sample form showing automatic entry of the User ID field:


Here is a picture of a simple form showing table [customers] setting [user_id] automatically via our new afterRecordInsert event.

OK, that’s it for this post. I really just wanted to test Servoy screenshots in Word Press. They seem to work OK, even on a phone, so I will create more in future. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *