Свежайшие Пирожки от CakePHP по-русски

Полнейшее руководство CakePHP 1.2 на русском языке, горячие новости и полезные статьи

Проверка данных из контроллера

While normally you would just use the save method of the model, there may be times where you wish to validate the data without saving it. For example, you may wish to display some additional information to the user before actually saving the data to the database. Validating data requires a slightly different process than just saving the data.

First, set the data to the model:

Простой текст
  1. $this->ModelName->set( $this->data );

Then, to check if the data validates, use the validates method of the model, which will return true if it validates and false if it doesn't:

Простой текст

  1. if ($this->ModelName->validates()) {
  2. // it validated logic
  3. } else {
  4. // didn't validate logic
  5. }

The validates method invokes the invalidFields method which populates the validationErrors property of the model. The invalidFields method also returns that data as the result.

Простой текст
  1. $errors = $this->ModelName->invalidFields(); // contains validationErrors array

It is important to note that the data must be set to the model before the data can be validated. This is different from the save method which allows the data to be passed in as a parameter. Also, keep in mind that it is not required to call validates prior to calling save as save will automatically validate the data before actually saving.

To validate multiple models, the following approach should be used:

Простой текст
  1. if ($this->Model->saveAll($this->data, array('validate' => 'only')) {
  2. // validates
  3. } else {
  4. // does not validate
  5. }