trying to use the beforeSave hook with some server side validation and throwing a field error – and it is working ….. kind of ….
There is an exception caused because it doesn’t save as required and the base exception can be viewed with the right message if no field is defined. If I define field then I don’t see the error popup or the error info on the crud form.
To be clear, its not letting me save and throwing the exception. When I use setField('fiscal_year') Its still not saving as per the exception, its just not displaying the exception.
Code below:
class Model_Finances extends Model_Table {
public $table='finances';
function init() {
parent::init();
$this->hasOne('Grant');
$this->addField('fiscal_year')->datatype('int');
$this->addField('requested')->datatype('money');
$this->addField('committed')->datatype('money');
$this->addField('spent')->datatype('money');
$this->getField('grant')->hidden(true);
$this->addHook('beforeSave',$this);
}
function beforeSave($model){
$exist = $this->api->db->dsql()
->table($this->table)
->field('count(1)')
->where('grant_id', 2) //manually set ID for testing.
->where('fiscal_year', $model['fiscal_year'])
->do_getOne();
// Validate fiscal year before saving
if($exist[0]) {
throw $this->exception('Fiscal year for this grant already exists')->setField('fiscal_year');
}
}
}
How it’s being used:
$finances = $grant->ref('Finances');
$finances->getField('fiscal_year')->setValueList($this->fiscalYears)->mandatory(true);
$crud=$tabs->addTab('Finances')->add('CRUD');
$crud->setModel($finances);
if($crud->grid)$crud->grid->addTotals(array('requested', 'committed', 'spent'));
It was quite difficult to reproduce the problem, so I created a test-case out of it.
I have changed only this line:
and here is result
If you submit form like this:
Then exceptions generated inside model->blah will also show up nicely.