我尝试按照CakePHP博客教程(http://book.cakephp.org/2.0/en/tutorials-and-examples/blog/blog.html)进行操作,除编辑方法外,一切正常。教程中指定的编辑功能似乎有效,但它不是更新旧条目,而是在数据库中创建一个新条目。 (但是说它确实使用&#34更新了旧条目; Jop已更新"消息)
我的源文件是:
edit.ctp
<html>
<!-- File: /app/View/Jobs/edit.ctp -->
<h1>Edit Job</h1>
<?php
echo $this->Form->create('Job');
echo $this->Form->input('type');
echo $this->Form->input('name');
echo $this->Form->input('company');
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->end('Save Job');
?>
</html>
JobsController.php
class JobsController extends AppController
{
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
public function index()
{
$this->set('jobs', $this->Job->find('all'));
}
public function view($id=null) {
if (!$id)
{
throw new NotFoundException(__('Invalid job'));
}
$job = $this->Job->findById($id);
if (!$job)
{
throw new NotFoundException(__('Invalid job'));
}
$this->set('job', $job);
}
public function add() {
if ($this->request->is('POST')) {
$this->Job->create();
if ($this->Job->save($this->request->data))
{
$this->Session->setFlash(__('Your job has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash('Unable to add your job.');
}
}
public function edit($id=null) {
if (!$id) {
throw new NotFoundException(__('Invalid job'));
}
$job = $this->Job->findById($id);
if (!$job) {
throw new NotFoundException(__('Invalid job'));
}
if ($this->request->is(array ('POST', 'PUT'))) {
$this->Job->id = $id;
if ($this->Job->save($this->request->data)) {
$this->Session->setFlash(__('Job has been updated.'));
return $this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash(__('Unable to update the job.'));
}
if (!$this->request->data) {
$this->request->data = $job;
}
}
}
public function delete($id) {
if (!$id) {
throw new NotFoundException(__('Invalid job'));
}
if ($this->request->is('GET')) {
throw new MethodNotAllowedException();
}
if ($this->Job->delete($id)) {
$this->Session->setFlash(__('Job has been deleted.'));
}
else {
$this->Session->setFlash(__('Unable to delete job.'));
}
return $this->redirect(array('action' => 'index'));
}
}
?>
答案 0 :(得分:1)
如果其他人遇到此问题,这是适用于我的解决方案:
if (!$this->request->data) {
$this->request->data = $job;
}
缩进错误,它不应该在
之内if ($this->request->is(array ('POST', 'PUT')))
阻止,但是在同一级别,即一个较少缩进的层。
答案 1 :(得分:0)
请检查您缺少的edit.ctp页面。
<?php echo $this->Form->create('Job'); ?>
<?php
echo $this->Form->hidden('id', array('value' => $this->data['Job']['id'])); ?>