Dynamic Fields Validation in CakePHP


In this post we'll learn about dynamic fields validation .Generally validation is achieved by placing the validation rules in the model file.You can get the idea of how validation rules are written in model file by the example given below.

<!-- file:app/models/yourmodel.php -->

var $validate = array(
'name' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'This field is required..!',
//'allowEmpty' => false,
//'required' => false,
//'last' => false,
//'on' => 'create',
),
),
'SRRP' => array(
'numeric' => array(
'rule' => array('numeric'),
'message' => 'This field is required..!',
//'on' => 'create',
),
)
);


But here,the fields (Example: name,SRRP) are static fields.Following lines of code were written in view file to generate them. 

<!--file:app/views/(yourmodel)s/add.ctp-->

   echo $this->Form->input('name');
   echo $this->Form->input('SRRP');


Because they were static its easy to validate them.For the dynamic fields,you can provide validation in controller file..!! Yes in controller file.

I have three dynamically generated fields called : title1 , title2 , title3 (in my case max limit of adding this field is 3).So how to handle validation rules for these fields? Add the following code in your controller's add function and as well as in edit function also.


<!-- File:app/controllers/yourcontroller-->

public function add()

 {
   if ($this->request->is('post')) {
      $this->Model->create();
       
   if (!empty($this->request->data)){
         $validate = array();
       $fields =array();
//Because my suffix starts with 1 (title1) and max limit of this field is 3
      for($i=1;$i<4;$i++)
          {
           $fields[]='title'.$i;
}

   foreach($fields as $field)

         {
$validate[$field] = array(
       'required'=>array(
       'rule'=>'notEmpty',
       'message'=>'Cannot be empty'
         )
         );
        }

   $this->Model->validate = $validate;
for($i=1;$i<4;$i++)
   {
if(!empty($this->data['Model']['title'.$i]))
   {
    $title=$this->data['Model']['title'.$i];
    $this->request->data['Model']['title'.$i] = $title;
   }
   }

     if ($this->Model->save($this->request->data)) {
        $this->Session->setFlash('Your data has been saved.');
        $this->redirect(array('action' => 'index'));
      }
    else {
            $this->Session->setFlash('Unable to add data.');
          }
        }
    }
}



If you have any queries then please comment here.

Comments

Popular posts from this blog

How to show only month and year fields in android Date-picker?

How to construct a B+ tree with example

Conflict Serializability in database