2013-03-25 40 views
0

我有一个cakephp 2.2应用程序,我正在研究这个应用程序,它允许用户提交费用索赔。这个早期的索赔是由许多有费用代码的老人组成的。的关系如下:在HMBTM领域进行表单验证 - CakePHP

ExpenseClaim的hasMany费用 费用属于关联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方法,它看起来像这样:

/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' 
    ) 
) 

正如你可以看到费用代码是空的...我怎样才能确保这不是这种情况?

回答

0

我设法解决这个问题通过添加以下到我的费用模型:

function beforeValidate() { 

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

希望帮助别人。

+0

但是,这并没有添加到有问题的字段的形式错误类可以喘口气SO和谷歌我无法找到一个解决方案。 – 2013-03-27 11:52:49