0

我有一个我正在开发的 cakephp 2.2 应用程序,它允许用户提交费用索赔。费用报销由许多具有费用代码的费用组成。关系如下:

ExpenseClaim hasMany Expense Expense belongsTo ExpenseClaim Expense hasAndBelongsToMany ExpenseCode

我想添加验证以确保表单完成时,每个费用的费用代码都必须完整,但由于某种原因,向费用模型添加正常的验证规则不起作用,显然我遗漏了一些东西。

以下是费用模型中的验证:

class Expense extends AppModel {

/**
 * Display field
 *
 * @var string
 */
    public $displayField = 'id';

/**
 * Validation rules
 *
 * @var array
 */
    public $validate = array(
        'date' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Date cannot be blank',
            ),
        ),
        'sitename' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Sitename cannot be blank',
            ),
        ),
        'detail' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Details cannot be blank',
            ),
        ),
        'ExpenseCode' => array(
            'multiple' => array(
                'rule' => array('multiple', array('min' => 1)),
                'message' => 'You need to select at least one tag',
              ),
        ),

当 $this->request->data 通过expenseClaim/add 方法提交时,它看起来像这样:

 /app/Controller/ExpenseClaimsController.php (line 179)

array(
    'submit' => 'Save',
    'Expense' => array(
        (int) 0 => array(
            'date' => array(
                'day' => '25',
                'month' => '03',
                'year' => '2013'
            ),
            'sitename' => '123',
            'detail' => 'test',
            'ExpenseCode' => array(
                'ExpenseCode' => ''
            ),
            'billable' => '1',
            'amount' => '100',
            'miles' => '',
            'total' => '100',
            'billable_mileage' => '',
            'recorded_global_mileage_rate' => '0.4'
        )
    ),
    'CashFloat' => array(
        'amount' => ''
    ),
    'ExpenseClaim' => array(
        'user_id' => '16',
        'claim_status_id' => '1',
        'date_submitted' => '2013-03-25 18:20:53'
    )
)

如您所见,ExpenseCode 为空...我如何确保不是这种情况?

4

1 回答 1

0

我设法通过在我的费用模型中添加以下内容来解决这个问题:

function beforeValidate() {

    if (!isset($this->data['ExpenseCode']['ExpenseCode']) || empty($this->data['ExpenseCode']['ExpenseCode'])) {
        $this->invalidate('ExpenseCode', 'Type cannot be blank');
    }
    return true;
}

希望对某人有所帮助。

于 2013-03-26T12:26:54.263 回答