2012-03-10 119 views
0

我一直在使用cakephp,并且已经能够创建一些简单的模型和关系。我一直在专门尝试实施hasMany关联。我的问题来自尝试更新子项目。CakePHP字段没有在编辑页面上更新

就我的例子而言,我假定我有一个'Parent'和'Child'模型类。我能够创建视图并添加页面而没有任何问题。不过,我并没有在编辑页面上取得同样的成功。在编辑页面上,我可以同时显示父字段和子字段。但是,当我去保存表单时,而不是更新子项,它只是添加现有的那些行。我不确定为什么会发生这种情况。我在某处丢失了一个参数吗?

这是我的编辑页面

echo $this->Form->create('Parent', array('action' => 'edit')); 
echo $this->Form->input('title'); 
echo $this->Form->input('body', array('rows' => '3')); 
echo $this->Form->input('id', array('type' => 'hidden')); 

$x = 0; 
foreach($this->request->data['Child'] as $child){ 
    print $this->Form->input("Child.$x.name"); 
    $x++; 
} 

代码这是我ParentController编辑功能

public function edit($id = null) { 
    $this->Parent->id = $id; 
    if ($this->request->is('get')) { 
     $this->request->data = $this->Parent->read(); 
     } else { 
      if ($this->Parent->saveAll($this->request->data)) { 
       $this->Session->setFlash('Your post has been updated.'); 
       $this->redirect(array('action' => 'index')); 
      } else { 
       $this->Session->setFlash('Unable to update'); 
      } 
     } 
} 
+0

你看看你的源代码,以确保表单动作/控制器/编辑/ ID,而不仅仅是/控制器/编辑?由于您假设id的默认值为null,因此可能会发生这种情况。 – 2012-03-11 09:34:43

+0

在任何人跳过我的喉咙,指出他有$ this-> data ['Parent'] ['id']作为隐藏字段时,通过将$ this-> Parent-> id设置为$ id,这将被忽略。如果$ id为空,它将插入新行。 – 2012-03-11 09:36:35

回答