1

尝试将 beforeSave 钩子与一些服务器端验证一起使用并引发字段错误 - 它正在工作......有点......

由于未按要求保存而导致异常,如果未定义任何字段,则可以使用正确的消息查看基本异常。如果我定义字段,那么我看不到错误弹出窗口或 crud 表单上的错误信息。

需要明确的是,它不会让我保存并抛出异常。当我使用setField('fiscal_year')它仍然没有根据异常保存时,它只是不显示异常。

下面的代码:

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');
        }
    }
}

它是如何被使用的:

    $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'));
4

2 回答 2

1

It was quite difficult to reproduce the problem, so I created a test-case out of it.

I have changed only this line:

throw $this->exception('Fiscal year for this grant already exists','ValidityCheck')
    ->setField('fiscal_year');

and here is result

enter image description here

If you submit form like this:

$form->onSubmit(function($f){
    $f->model->blah();
});

Then exceptions generated inside model->blah will also show up nicely.

于 2012-10-12T00:30:43.883 回答
0

我想我不会完全回答你的问题,因为我也是 ATK4 的初学者,但是

首先我猜你不应该在模型级别使用 $_GET 。我相信它应该类似于grant_id=$model['grant_id']。

其次,据我了解,您想检查一个补助金是否有唯一的财政年度?如果是这样,那么您应该在 WHERE 中添加另外两个条件(见下文)或类似的条件。

结果我相信你的查询应该是这样的(只是一个伪代码):

$exist = $this->api->db->dsql()
                   ->table($this->table)
                   ->field('count(*)') // I guess it can be written as ->count() too
                   ->where('grant_id',$model['grant_id'])
                   ->where('id','!=',$model->id)
                   ->where('fiscal_year',$model['fiscal_year'])
                   ->do_getOne();
if($exist[0]) {
    throw $this->exception('Fiscal year for this grant already exists')
               ->setField('fiscal_year');
}

说到抛出与表单字段相关的异常,我想您应该以某种方式使用表单字段验证钩子添加它。但我不知道该怎么做。

于 2012-09-27T13:31:58.777 回答