tags:

views:

24

answers:

2

How do you set up dynamic property defaults on CF9 ORM objects?

For instance, I know I can set a property default like this:

property name="isActive" default="1";

But what if you want to have a dynamically generated default, such as a date or a UUID?

property name="uuid" default="#createUUID()#";

...throws an error - so what's the workaround for this?

A: 

Have you tried overloading the getter?

public string function getUUID() {if(variables.UUID EQ ""){ return createUUID(); } else { return variables.firstName; }; }

I can't test that from where I'm at, but I would try.

ibjhb
Dan, I think he needs it to be a default and not always return a new UUID. What if the UUID already persists in the database?
ibjhb
+1  A: 

When an Entity object is created the objects constructor is called. This is a great place for running "setup" code.

User.cfc

component persistent="true"
{
  property name="id" fieldtype="id" generator="native";
  property name="secretKey";

  public User function init() {
     if (isNull(variables.secretKey))
         setSecretKey(createdUUID());

     return this;
  }
}
Dan Vega
This works fine for new entities, but is overwritten by anything that's loaded from the database (even if it's a blank value).However, since I'm building this app from scratch, with no legacy data, I can be sure that every entry in the users database will be created with this default.(In your code above, the init() function needs "return this;" added to the end.)Thanks,Seb
sebduggan
If you only want to run this code for a new entity you could always check the id of the entityif( isNull(getId()){ }
Dan Vega
an alternative would be to assign uuid @ preInsert
Henry
Link for Henry's suggestion to use orm event handler cfchttp://www.danvega.org/blog/index.cfm/2009/12/22/ColdFusion-9-ORM-Event-Handlers-Use-Case
David Collie