简体   繁体   中英

CakePHP2 validation on field not in table

I have 4 attributes in a table; num_a , num_b , num_c , num_d , these individually can be in a range of 0 to 2, eg I have in my $validate property in model:

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

The problem I am facing is that the sum of these must be greater than 0. I would like it to return some validation error if this is the case, eg:

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

I have the returnFalse function in my model which is simply

public function returnFalse() {
  return false;
}

to always add this rule.

In the beforeValidate I am checking the sum of num_a through num_d and removing the validation rule if $sum > 0 like so:

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');
  }
}

But for some reason I can not get this to return a validation error for num_all .

I even tried to add a virtual field so maybe the validation error had something to attach to:

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

but this didn't work either. I am using CakePHP v2.8.

OK, so I ditched the num_all in the $validate property and the virtual field, etc. and the 'always fails' rule, and instead hacked on an entry to the models validationErrors array in beforeValidate :

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->validationErrors['num_all'][] = 'There were no a, b, c or d selected.'
  }
}

And it works fine now. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM