编辑插入新行而不是更新cakephp 2x中的当前行

时间:2015-05-16 07:38:12

标签: cakephp edit

在我将user_id发送给学生资料后,我在更新学生资料表单方面遇到了麻烦。每当我尝试编辑表单时,保存它会为现有用户提供新的ID。我不知道我哪里出错了。 Plz help.Thanks in Advance。  这是我在学生档案控制器中的添加和编辑功能:

 public function add() {
   if ($this->request->is('post')) {
      $this->StudentProfile->create();
    $data = $this->request->data;
     $data['StudentProfile']['user_id'] = $this->Auth->user('id');
     // code implemented below               
     //$this->loadModel('User');

      if ($this->StudentProfile->save($data)) {
        //Update user here if Profile saved successfully 
        //$this->StudentProfile->id = $this->Auth->user('id');

            $this->Session->setFlash(__('Your account profile has been   created'));
            $this->redirect(array('controller' => 'studentprofiles',   'action' => 'index'));
        }else{
             $this->Session->setFlash(__('Your Profile was saved, but an  error has occurred while updating the Users table'));
            //Email your self the user ID here or something ??
        }
    } 
     $h=array(

  'fields' => array('Height.height'),
  'recrusive' => 0
);

    $this->loadModel('Height');
    $height = $this->Height->find('list',$h);
    $this->set(compact('height'));
}

public function edit($id = null) {
      if (!$this->StudentProfile->exists($id)) {
        throw new NotFoundException(__('Invalid student profile'));
      }
     if ($this->request->is(array('post', 'put'))) {
        $this->request->data['StudentProfile']['user_id'] = $this->Auth- >user('id');
      // code implemented below               
     // $this->loadModel('User');
        if ($this->StudentProfile->save($this->request->data)) {
            //$this->StudentProfile->id = $this->Auth->user('id');
            $this->Session->setFlash(__('The student profile has been   saved.'), 'default', array('class' => 'alert alert-success'));
            return $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The student profile could not be   saved. Please, try again.'), 'default', array('class' => 'alert alert-danger'));
        }
    } else {
        $options = array('conditions' => array('StudentProfile.' . $this-  >StudentProfile->primaryKey => $id));
        $this->request->data = $this->StudentProfile->find('first',   $options);
    }
      $h=array(

  'fields' => array('Height.height'),
  'recrusive' => 0
);

    $this->loadModel('Height');
    $height = $this->Height->find('list',$h);
    $this->set(compact('height'));
 }

2 个答案:

答案 0 :(得分:0)

无法相信我回答了我自己的问题。好吧,如果有人遇到上述问题,解决办法就是在此之后添加以下代码 -

 $this->request->data['StudentProfile']['user_id'] = $this->Auth->user('id');
 // add this code to avoiding giving new id to existing user on edit:
        $this->request->data['StudentProfile']['id'] = $id;

答案 1 :(得分:0)

保存已编辑信息的更好方法是在保存之前在模型上设置ID,如此

$this->StudentProfile->id = $this->Auth->user('id');

如果在设置上述内容后启动保存,则将编辑该行,而不是添加新行。