CakePHP2验证字段不在表中

时间:2017-06-30 10:02:45

标签: php cakephp cakephp-2.8

我在表格中有4个属性; num_anum_bnum_cnum_d,这些可以分别在0到2的范围内,例如我在模型中的$validate属性中<:p>

'num_a' => [
  'numeric' => [
    'rule' => 'numeric',
    'message' => 'Please provide the number of a.',
  ],
 'isInRange' => [
   'rule' => ['range', -1, 3],
   'message' => 'Must be between 0 and 2.'
 ],

我面临的问题是这些问题的总和必须大于0.如果是这种情况,我希望它返回一些验证错误,例如:

'num_all' => [
  'rule' => 'returnFalse',
  'message' => 'There were no a, b, c or d selected.',
],

我的模型中有returnFalse函数,只是

public function returnFalse() {
  return false;
}

始终添加此规则。

beforeValidate我正在检查num_anum_d的总和,如果$sum > 0如此,则删除验证规则:

public function beforeValidate($options=array())
{
  $sum = 0;
  $sum += (isset($this->data['MyModel']['num_a'])) ? $this->data['MyModel']['num_a'] : 0;
  $sum += (isset($this->data['MyModel']['num_b'])) ? $this->data['MyModel']['num_b'] : 0;
  $sum += (isset($this->data['MyModel']['num_c'])) ? $this->data['MyModel']['num_c'] : 0;
  $sum += (isset($this->data['MyModel']['num_d'])) ? $this->data['MyModel']['num_d'] : 0;

  if ($sum > 0) {
    $this->validator()->remove('num_all');
  }
}

但出于某种原因,我无法通过num_all返回验证错误。

我甚至尝试添加虚拟字段,因此可能验证错误有附加内容:

public $virtualFields = [
  'num_all' => 'SELECT 0 FROM dual',
];

但这也不起作用。我正在使用CakePHP v2.8。

1 个答案:

答案 0 :(得分:0)

好的,所以我放弃了num_all属性中的$validate和虚拟字段等,以及'总是失败'规则,而是攻击了模型{{1}的条目validationErrors中的数组:

beforeValidate

现在它运作正常。希望这会有所帮助。