我尝试按照 CakePHP 博客教程 (http://book.cakephp.org/2.0/en/tutorials-and-examples/blog/blog.html) 进行操作,一切正常,除了编辑方法。教程中指定的编辑功能似乎有效,但它没有更新旧条目,而是在数据库中创建了一个新条目。 (但是说它确实用“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'));
}
}
?>
最佳答案
如果其他人有这个问题,这是对我有用的解决方案:
if (!$this->request->data) {
$this->request->data = $job;
}
缩进错了,不应该在
内if ($this->request->is(array ('POST', 'PUT')))
block ,但在同一层,即缩进少一层。
关于php - 在 CakePHP 中编辑创建新条目而不是更新旧条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36362184/