如何在cakephp将数据放入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'));
}
}
我的数据库中的字段:
模板
任何人都可以帮助我吗?
问候!
答案 0 :(得分:2)
正确的方法是将它放在模型中,而不是放在控制器中(因为你正在处理数据,所以它必须在模型中)。
为此,您可以使用model的“beforeSave”方法:
Cake1.2:http://book.cakephp.org/view/683/beforeSave
Cake1.3:http://book.cakephp.org/view/1052/beforeSave
蛋糕2:http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave