Saturday 15 June 2013

php - how to validate form field in cakephp using model and controller -



php - how to validate form field in cakephp using model and controller -

i have created form need validate using model , controller .here form

index.ctp

<?php echo $this->form->create('contact',array('url'=>array('controller'=>'contacts','action'=>'add'))); echo $this->form->text('name');

model : contact.php

class contact extends appmodel { var $name = 'contact'; var $usetable = false; public $validate = array( 'name' => array( 'alphanumeric' => array( 'rule' => 'alphanumeric', 'required' => false, 'message' => 'letters , numbers only' ), 'between' => array( 'rule' => array('between', 5, 15), 'message' => 'between 5 15 characters' ) ) ); }

controller : contactscontroller.php

public function add() { $this->contact->validates(); $this->request->data['country']['country_name']=$this->request->data['contact']['country']; $this->country->saveall($this->request->data); $this->redirect('/contacts/index/'); }

i trying validation googling seems hard me if describe process great help .my cakephp version 2.3.8. need validate name field , when click in submit show message in form.

your controller code should process of validation in cakephp like

1) have defined validation rules in cakephp model public `$validates = array();` 2) when ever save on particular model straight or through association callback method beforevalidate model gets called validate info beingness saved. 3) 1 time info validated beforesave callback called after save method called. 4) can validate form input fields in controller using $this->model->validates() while saving have disable beforevalidate callback doing $this->model->save($data,array('validate'=>false));

otherwise end validating same info twice

your controller code should this.

public function add() { // here checking request post method if ($this->request->is('post')) { $this->request->data['country']['country_name'] = $this->request->data['contact']['country']; // here saving info if ($this->contact->saveall($this->request->data)) { //here setting flash message user $this->session->setflash('your record has been added','success'); $this->redirect(array('controller'=>'contacts','action' => 'index')); } else { //here setting flash message user error if input not //validated expected $this->session->setflash('sorry add together record','error'); } } }

for more info can refer http://book.cakephp.org/2.0/en/models/callback-methods.html

php cakephp cakephp-2.3

No comments:

Post a Comment