Tuesday, December 18, 2012

CakePHP: Save and Show

In this small code snippet I show how to store some formulary data corresponding to an ad, and after saving redirect to the page to show the stored values.
<?php

//...

class AdsController extends AppController {
  
 public function add() {  
        if ($this->request->is('post')) {
         if ($this->Ad->save($this->request->data)) {
              $this->Session->setFlash('The ad was saved!');
              $inserted_id = $this->Ad->id;              
              $this->redirect(array('action' => 'view', $inserted_id ));
         } else {
             $this->Session->setFlash('The ad could not be saved!');
         }
  }
  // ...
    }
    
 // ...
 
 public function view($id) {
        $this->Ad->id = $id;
        $this->set('ad', $this->Ad->read());
    }    
}
The key line is the redirect. It took me a while to figure out how could I pass the just inserted id to the view page.

No comments:

Post a Comment