Friday, 29 June 2012

simple cakephp CRUD operation

had some time to work on very popular framework cakephp, never find time and patience lookup the code generator console in cake. just jumped into coding and like to keep this handy... for creating a quick CRUD template 

 
<?php
simple crud operation in cakephp 2.x

create a controller which extend the base framework controller class
class TestsController extend AppController {
//read about class name convention in detail for the cakephp 

public $name = 'tests';
public $helper=array('Html','Form'); //for creating the form and html link in the view 
public function add(){
 if ($this->request->is('post')) {  //check whether request type is post before accepting the data 
            if ($this->Page->save($this->request->data)) {// save the data
                $this->Session->setFlash('Your data has been saved.'); // generate a flash message 
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('Unable to add your data.');
            }
        }
}


public function index(){
$this->set('test', $this->Test->find('all')); 
/* model which look up in the databases table "tests" and fetch all the content */ 
}

public function edit($id = null){
          $this->Test->id = $id;   // set the id to the model id value
                 if ($this->request->is('get')) { // check request type
               $this->request->data = $this->Test->read(); //read record with id and display the form regularly 
                 } else {
                      if ($this->Test->save($this->request->data)) {  // if post request save the data
                          $this->Session->setFlash('Your data has been updated.');
                          $this->redirect(array('action' => 'index'));
                     } else {
                          $this->Session->setFlash('Unable to update your data.');
                 }
}

   public function view($id=null){
        $this->Test->id = $id; //action to display the content or view the content
        $this->set('test', $this->Test->read());
   }

 public function delete($id=null){ // critical action 

   if ($this->request->is('get')) {
        throw new MethodNotAllowedException(); // throw error if request is get and break
        }
  
            if ($this->Test->delete($id)) { // deleted 
                 $this->Session->setFlash('The page with id: ' . $id . ' has been deleted.');
                  $this->redirect(array('action' => 'index'));
           
               }

}



}
?>