if($this->request->data['Model']['field'] > 0) { $this->Session->setFlash(«message»); $this->redirect($this->referer()); } if($this->request->data['Model']['field'] == «string») { $this->Session->setFlash(«message»); $this->redirect($this->referer()); }
array( 'Model' => array(field_list))
echo $this->Form->create('Model'); echo $this->Form->input('first_field', array('type' => 'text')); echo $this->Form->input('second_field', array('type' => 'text)); echo $this->Form->end();
App::uses('Form', 'Forms.Lib/Form'); class ExampleForm extends Form { public $model = 'Example'; public $fields = array( 'first_field' => array( 'type' => 'text', ), 'second_field' => array( 'type' => 'text', ) ); public $validate = array( 'second_field' => array( 'isActive' => array( 'rule' => 'isActive', 'message' => "Is fields not active!" ), ), 'first_field' => array( 'aboveZero' => array( 'rule' => 'aboveZero', 'message' => "Number must be greater than 0", ), ), ); /** * @return bool */ public function isActive(){ if(isset($this->options['user_id'])) { return false; } return (bool)$this->data[$this->model]['second_field']; } /** * @return bool */ public function aboveZero() { return (is_numeric($this->data[$this->model]['first_field']) && ($this->data[$this->model]['first_field'] > 0)); } }
class ExamplesController extends AppController { public $name = 'Examples'; public $uses = array( 'Example', ); public $components = array( 'Forms.FormValidator' ); public $forms = array( 'ExampleForm', ); /** * Example validation html-form data in $this->request->data */ public function example() { if ($this->ExampleForm->validates($this->request->data)) { echo 'true validations'; } else { echo 'false validation'; } } }
public function example2() { $data = array( 'Example' => array( 'first_field' => 0, 'second_field' => true ) ); if ($this->ExampleForm->validates($data)) { echo 'true validations'; } else { echo 'false validation'; } }
public function example3() { $data = array( 'Example' => array( 'first_field' => 0, 'second_field' => true ) ); $this->ExampleForm->addOptions(array('user_id' => $this->Auth->user('id'))); if ($this->ExampleForm->validates($data)) { echo 'true validations'; } else { echo 'false validation'; } }
Source: https://habr.com/ru/post/197928/
All Articles