有人能向我解释一下吗?我正在尝试编写一个编辑操作,但有点不确定为什么以下操作不起作用:
public function edit($id = null) {
if (!$id) {
throw new NotFoundException('NO ID HAS BEEN SUPPLIED');
}
$data = $this->User->findById($id);
if(!$this->request->is('post')) { $this->request->data = $data; }
if($this->request->is('post') || $this->request->is('put')) {
$this->User->id = $id;
$this->User->save($this->request->data);
$this->redirect(array('action'=>'index'));
}
}
不工作,我的意思是,虽然它确实用从findById($id)收集的数据预填充了表单。。在表单发送后,它不会用新的输入更新数据库。
我已经替换了这个:
if(!$this->request->is('post'))
带有以下内容:
if($this->request->is('get'))
突然间,它工作得很好。它使用从帖子中收集的新值更新行。然而,我不明白这里发生了什么。为什么是那样$this->request->is('post'),不起作用,而$this->quest->is('get')起作用?当然,当第一次调用操作时,它是使用GET请求调用的吗?这个请求不符合$这个->请求->是("成本")?
编辑:
下面是ctp:app/View/Users/edit.ctp
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('edit User'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('role');
// echo $this->Form->input('role', array(
// 'options' => array('admin' => 'Admin', 'regular' => 'Regular')
//));//
?>
</fieldset> <?php echo $this->Form->end(__('Submit')); ?>
默认情况下,Cake使用'PUT'方法执行'edit'操作,使用'POST'方法进行'add'操作。因此您需要检查$this->request->isPut()
(或$this->request->is('put')
)。在视图中查找由$this->Form->create()
方法自动生成的hiiden字段*_method*。
如果在传递给视图的数据中设置了"id"属性,Cake将创建"edit"表单,如果没有"id"则创建"add"。
这样做
public function edit() {
$id = $this->params['id'];
if (!$id) {
throw new NotFoundException('NO ID HAS BEEN SUPPLIED'); }
$data = $this->User->findById($id);
if(!$this->request->is('post')) { $this->request->data = $data; }
if($this->request->is('post') || $this->request->is('put')) {
$this->User->id = $id;
$this->User->save($this->request->data);
$this->redirect(array('action'=>'index'));}
从url传递id进行编辑不是一种安全的方式。。。$this->params['id']
会有你的帖子id,所以有了它CCD_ 5将起作用。