i’am a cakephp newbie 😀
how can i modify data in a controller before cakephp put the data into mysql?
function add() {
if (!empty($this->data)) {
$this->Template->create();
/* This works! */
$this->data['Template']['slug'] = Inflector::slug(utf8_encode(strtolower($this->data['Template']['name'])),'-');
/* does not work ! */
$this->data['Template']['created'] = time();
$this->data['Template']['category_id'] = $this->data['Template']['category'];
if ($this->Template->save($this->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
}else{
/* dropdown */
$this->set('categories',$this->Template->Category->find('list'));
}
}
Fields in my database:
templates
- id
- slug
- category_id (belong to categories)
- name
- created
Can anyone help my?
greetings!
The correct way is putting it in your Model, not in your controller (because you are treating data, so it must be in the model).
For this, you can use model’s “beforeSave” method:
Cake1.2: http://book.cakephp.org/view/683/beforeSave
Cake1.3: http://book.cakephp.org/view/1052/beforeSave
Cake 2: http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave