Pages

Saturday, March 24, 2012

(CakePHP) Change validation rule for a field in controller.

In this blog post I'm going to explain how to add different validations for same field in different function in
controller.
For example 
in one view(greaterthanadd.ctp) i wanted to add number which is grater than 18.
and in other view(lesserthanadd.ctp) i wanted to add number which is less than 18.
This is doing for the same database table same column.
In CakePHP (1.3) we can call modle using
$this->Model_name;
So we can access the validation array in controller
$this->Model_name->validate['fieldName']['ruleName'];
In this example I am using table called numbers and field call number.
function greaterthanadd() { 
   if (!empty($this->data)) { 
//************
//validation strat
//************ 
     $this->Number->validate['number']['greaterthan'] = array(
          'rule' => array('comparison', '>=', 18), 
          'message' => 'Must be at least 18.'); 

//************
//validation end
//************ 

     if ($this->Number->save($this->data)) { 
        $this->Session->setFlash(__('The number has been saved', true)); 
        $this->redirect(array('action' => 'index')); 
     } else {
        $this->Session->setFlash(__('The number could not be saved. Please, try again.', true)); 
             } 
      } 
}


function lesserthanadd() {
      if (!empty($this->data)) {

//************
//validation strat
//************ 

       $this->Number->validate['number']['greaterthan'] = array(
            'rule' => array('comparison', '<=', 18),
            'message' => 'Must be at least 18.');

//************
//validation end
//************ 

       if ($this->Number->save($this->data)) {
           $this->Session->setFlash(__('The number has been saved', true));
           $this->redirect(array('action' => 'index'));
            } else {
           $this->Session->setFlash(__('The number could not be saved. Please, try again.', true));
            }
        }
    }