# CCK and Computed Fields

I've been using the great CCK module on a bunch of projects (including this blog, for my bikelog). It's really cool in that it lets you construct custom content types within the Drupal admin interface, without having to touch any PHP code. It's like having your own personal microformat manager - it could handle things like compound content on a web page (and generate the editing form so you just fill in the blanks - abstract, body, url for more info, email contact, etc...) and I think it could even handle something like a simplified LOM for a "learning object repository".

One thing I wanted to do on my bikelog was to automatically calculate average speed. I have fields for "duration" and "distance" so entering a value for "average speed" is redundant. Better to just derive the value from the known values already entered.

Which is where the really cool Computed Field module comes in. It's a contributed module for CCK, and lets you do all kinds of funky things by writing PHP code to perform operations to generate the value of a field. These operations can include calculations on the other fields, or even more complicated things like, I suppose, performing a lookup on wikipedia or something...

After adding the Computed Field module, I just edited my "bikeride" CCK content type to add a new "computed" field called "average speed". It's got a "computed code" value, which is executed whenever a value needs to be derived. I just used this:

$node_field[0]['value'] = ($node->field_distance[0]['value'] / \$node->field_duration[0]['value']) * 60;

I gave it a data type of "float", a length of "10,2" and a default value of 0. I told the module to store the value in the database, so I can use the computed field with Views.module as well (in this case, it performs the computation on edit, and stores the result in a field just as any other CCK field would do). I also flagged the field as being sortable, in case that helped Views.module at all.

The end result is a tiny bit of work entering a simple PHP calculation, and then the module takes over the monotonous and redundant calculation work. All I do is enter the base data, and it can derive the rest from that.

I'd imagine this type of derived field could be really useful in an event manager - looking up the number of registrations and updating an "available seats" field, for instance. Or, in a store or inventory system to calculate prices and stock counts. It's a really cool addition, and although the setup interface (manually entering PHP code) isn't something you'd unleash on a noob, it's simple enough to set up and forget about.