This is probably not life altering news for most. However, after spending a couple hours tracking down how to do something I figured I would blog it. What I was trying to do was setup an preupdate and preinsert events on a specific entity. I have previously setup global events so I figured this would be a slam dunk.

But first, what are event handlers and what can you do with them? Well, think of them as database triggers. They could be used to log record updates, or even data loads for that matter. You can find a full list of them here:

To use event handlers you first need to enable them in your application. This is accomplished by updating the orm settings in your application.cfc file. The eventhandler setting is required if you are using global events.

view plain print about
1this.ormsettings = {
2eventhandling= "true",
3eventhandler - "your.event.cfc"

As an example, lets say we want to update an created date any time a record is inserted. Instead of going to all your code where the entity is created it makes much more sense to add an event handler.

view plain print about
1public void function preInsert(any entity){
2        var thisTable = getMetadata(arguments.entity).table;
3        if (thisTable == 'myTable'){
4            entity.setCreateDate(now());
5        }
7    }

In the code example above we run a preInsert event. The code checks for the table being inserted into and if it is the correct table, the create date is set.

This works just fine but it probably not a good candidate for a global event. This is more something that should be on the specific entity. This can be done by adding that same function, with some slight modifications, to the persistant cfc for the table.

view plain print about
1public void function preInsert(){
2        this.setCreateDate(now());
3    }

This is the part that tripped me up. The function is about the same with the exception of the arguments. Notice that for the entity specific function there are none. Also, to set the create date we use the "this" scope. The documentation from Adobe on event handlers gives poor, or non-existant examples of event handlers. So, trial and error, and google helped me figure this out.

So there you have it, when dealing with global events you need to reference the arguments scope when dealing with the entity. But, when dealing with a specific entity the "this" scope is utilized.


The great John Whish pointed out a couple other ways to accomplish this as well. Apparently the "this" scope is not necessary. You can also sit it without using the set method. I tried both of these and they worked just fine.

view plain print about
1public void function preInsert(){
2        setCreateDate(now());
3    }
5    public void function preInsert(){
6        variables.CreateDate = now();
7    }

Till next time,