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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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.