在HMBTM字段上进行表单验证 - CakePHP

时间:2013-03-25 17:22:26

标签: cakephp validation

我有一个cakephp 2.2应用程序,我正在努力,允许用户提交费用索赔。该费用由许多有费用代码的费用组成。关系如下:

ExpenseClaim有很多费用 费用属于ExpenseClaim 费用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',
              ),
        ),

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

 /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是空的......我怎样才能确保不是这种情况?

1 个答案:

答案 0 :(得分:0)

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

function beforeValidate() {

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

希望能有所帮助。