For my timetracker i have a field worktime containing the minutes worked on a project. For convenience i’d like to automatically convert this to hour:minutes and also use hours/minutes in forms. I thought about adding this to the AR:
<?php
public $minutes;
public $hours;
public function afterConstruct()
{
if ($this->worktime) {
$this->minutes=$this->worktime%60;
$this->hours=floor($this->worktime/60);
}
}
public function beforeSave()
{
$this->worktime=$this->hours*60+$this->minutes;
}
But afterConstruct() doesn’t seem to be called for every record returned by findAll(). So is my approach a bad idea?
As written above i use the 2 “virtual” attributes hours and minutes. I added both to safeAttributes() and now can easily work with hours and minutes in my form, that get automatically converted to minutes on save. So far so good
I also added some validation:
<?php
public function rules()
{
return array(
// ...
array('worktime', 'validatetime'),
);
}
public function validatetime($attribute,$params)
{
if (!$this->minutes && !$this->hours)
$this->addError('worktime','Time can not be empty');
}
If both fields are empty, the activeLabel get’s the error class set. But not the two activeTextFields. Is there a way to achieve this?
My idea was to do this:
<?php
if (!$this->minutes && !$this->hours) {
$this->addError('worktime','Time can not be empty');
$this->addError('hours');
$this->addError('minutes');
But addError() always expects a second parameter. Would it make sense to make this parameter optional? If it's empty only an errorclass is added to the active fields, but no errormessage is shown.