The problem with this approach is that it will only store elapsed time when adding a record using the new record form. It won't update the elapsed time when you update the record, or if you add records programmatically, or if you add them via the new related record form.
If you really want to store the elapsedTime as its own physical field in the database (rather than a calculated field) you should probably do the calculation in the beforeSave() trigger:
- Code: Select all
function beforeSave(&$record){
$record->setValue('elapsedTime', $record->val('endTime')-$record->val('startTime'));
}
Note: this example assumed that endTime and startTime are stored in the database as integers so we can do the simple subtraction. If they are stored as dates or timestamps you must first convert them to integers for this arithmetic to work. E.g.:
- Code: Select all
$startTimeSeconds = strtotime($record->strval('startTime'));
Another way that may be better is to not store the elapsedTime field in the database at all, but rather leave it as a calculated field. You can do this via the __sql__ directive in the fields.ini file:
- Code: Select all
__sql__ = "select t.*, timediff(endTime, startTime) as elapsedTime from mytable t"