Just do PRG Pattern..It's very simple right?! Well, at least that's what everyone says but no one posts a clear answer! It took me a week of search and digging and then the "Newbie" decided to do something on his own! Here is one way to do it in cakephp (I use 2.0.5):
Regardless of code here is the logic in steps:
1- set data
2- validate (do NOT create() yet)
3- write $this->request->data to a session variable
4- redirect to a saveData action
Inside saveData action:
5- read & save the session's variable
6- DELETE session's variable
7- create()
8- save data to model
9- redirect
Here is an example of how your code might look like.
**Attn: "ourController" and "ourModel"
public function add() {
if ($this->request->is('post')) {
if (isset($this->request->data)) {
$this->ourModel->set($this->request->data);
if ($this->ourModel->validates()) {
$this->Session->write('myData', $this->request->data);
$this->redirect(array('controller' => 'ourController',
'action' => 'saveData',
'ourModel' //optional but recommended
)
);
} else {
$this->Session->setFlash('ourModel could not be saved.');
}
}
.....//the rest of add() function
}
Then you should be redirected (on validation) to this function that redirects you again to index action or wherever your logic takes you!
public function saveData($model) {
$myData = $this->Session->read('myData');
$this->Session->delete('myData'); //extremely important
$this->$model->create();
if ($this->$model->save($myData))
// or $myData[$model] if you are dealing with multiple models
{
$this->Session->setFlash(__($model.' have been saved successfully'));
$this->redirect(array('controller' => 'ourController',
'action' => 'index'
)
);
}
} else{
$this->Session->setFlash(__($model.' could not be saved'));
}
}
}
A simple self-redirect might work but in most cases you want to redirect to a different view (e.g. to another form or to index view)
I hope this elaboration helps save time on others so not to have to waste a whole week (as in my case) just to do such functionality server-side!