保存到数据库之前修改数据
我是 cakephp 新手 :D
在 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'));
}
}
我的数据库中的字段:
模板
- id
- slug
- Category_id(属于类别)
- 名称
- 已创建
任何人都可以帮助我吗?
问候!
i'am a cakephp newbie :D
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正确的方法是将其放入您的模型中,而不是放入控制器中(因为您正在处理数据,所以它必须位于模型中)。
为此,您可以使用模型的“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
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