+1 571-297-6383 | info@sonjara.com

Simplified DataItems and Calculated Fields

It has been a while since I got around to writing one of these, so here we go...

Simplified DataItems

This isn't a new feature as such, more a realization that we can tidy up the way we declare our DataItems now that PHP 4 is completely dead and buried and jumped up and down upon. Basically, we can ditch the old style constructors in our DataItems and declare the primary_key and table properties in the body of the class definition, like so:

class Meeting extends DataItem
{
    var $table = "meeting";
    var $primary_key = "meeting_id";
    
    var $fields = array("meeting_id" =>  Number,
                        "meeting_date" => Date,
                        "location" => String,
                        "description" => HTML,
                        "notes" => HTML);
}

There is no need to declare a constructor at all unless you need to do something programmatic each time your DataItem is instantiated. I think you'll agree this is significantly cleaner than the old way (as a bonus it is also more efficient).

Calculated Fields

This one is hot off the code press. Sometimes you want to have a field in your data model that is derived from other fields in the object, but you want to do so without denormalizing your database. For instance, you might want to extract the year from a date field to help with grouping in the user interface. One way to handle this is to define a view in the database that generates that field, but this is cumbersome and requires the definition of another DataItem to map the view.

To simplify this process, DataItems now have a feature called Calculated Fields. Calculated Fields are fields that map to SQL expressions which get automatically populated on your DataItem when the query is run against the database. For example, suppose we want to have the year derived from the meeting_date in the meeting object shown above. We can now add a calculated field for that like so:

class Meeting extends DataItem
{
    var $table = "meeting";
    var $primary_key = "meeting_id";
    
    var $fields = array("meeting_id" =>  Number,
                        "meeting_date" => Date,
                        "location" => String,
                        "description" => HTML,
                        "notes" => HTML);

    var $calculatedFields = array("year" => "YEAR(meeting_date)");
}

A few things to note:

  • Calculated Fields do not interact with AutoForms (being derived values they aren't editable).
  • The field gets populated on your DataItem as a property, the same as the fields in the $fields collection.
  • You can use calculated fields in format() templates and as the grouping field in grouped or indexed queries.
This is a very new feature (just added this morning). If you find any quirks with it, please let me know.


Little Things can make a Difference » « Taxonomies, Panels and Component Help (oh my!)
 

Comments

* indicates required field