所以我有一个正在开发的应用程序来处理由一个或多个帐户组成的事务。例如:购买100美元的沃尔玛购物可能有40美元来自杂货帐户,60美元来自家庭帐户。
表格大致是:
echo $this->Form->input('Transaction.user_id');
echo $this->Form->input('Transaction.description');
echo $this->Form->input('Transaction.amount');
echo $this->Form->input('AccountTransaction.0.account_id');
echo $this->Form->input('AccountTransaction.0.amount');
.
.
.
可能涉及一个或多个帐户交易。此外,AccountTransaction还有一个transaction_id字段。
提交表单后,我想:
所以我可以轻松地在控制器中执行这些操作,但我想知道是否有一种方法可以在Transactions模型中设置验证,以检查所有帐户事务是否在保存之前加起来。
答案 0 :(得分:2)
我终于意识到我可以使用$ this->数据查看所有数据,所以我添加了一个自定义验证检查所提交的所有内容。我最终获得了一个附加到正确元素的自定义验证消息,并且效果很好:
public function accountsBalance($check) {
$check = (float) $check['amount'];
$sum = 0;
foreach($this->data['AccountTransaction'] as $account) {
$sum += $account['amount'];
}
if ($sum==$check)
return true;
$diff = $check-$sum ;
$message = sprintf("This doesn't match what you entered in your accounts. The total for the accounts is $%0.2f. You're too %s by $%0.2f",
$sum, $diff > 0 ? "high": "low", abs($diff));
$this->validator()->getField('amount')
->getRule('balance')->message = $message;
return false;
}
然后对于我的规则:
public $validate = array(
'amount' => array(
'notempty' => array(
'rule' => array('notempty'),
),
'balance' => array(
'rule' => array('accountsBalance'),
'message' => 'The total needs to match your account entries'
)
),
);
答案 1 :(得分:1)