2013-11-15 8 views
-1

我有2個簡單的模型:CakePHP 2.4 - 如何在編輯之前在其他模型中保存數據副本?

進入

  • ID
  • 標題
  • 內容
  • USER_ID
  • CATEGORY_ID

存檔

  • ID
  • 標題
  • 內容
  • 原因
  • USER_ID
  • CATEGORY_ID
  • entry_id

我想問我怎麼能保存副本入口的作爲存檔編輯之前,並添加編輯的原因是什麼?我想這是CakePHP中最正確的方法。

這將是將數據添加到存檔模型(編輯條目)的唯一方法。

我應該在Entry中包含Archive模型,在編輯函數中創建()存檔,從Entry中複製數據,從編輯表單中手動添加原因並在編輯完成時保存()。

我只有在編輯時才需要此功能。其他行動將是標準的。

+0

你試過了什麼?請發佈您嘗試的解決方案,並告訴我們什麼不起作用 – StormeHawke

回答

0

修改請求數據,像這樣:

$this->request->data['Archive'] = $this->request->data['Entry'] 
$this->request->data['Archive']['entry_id'] = $this->request->data['Entry']['id'] 
unset($this->request->data['Archive']['id']); // don't need this for archives 

這樣的要求既有檔案,並在其中錄入數據。您可以在條目編輯表單中包含編輯的原因。由於沒有輸入字段有理由..它不會被保存。同時考慮使用saveAll方法,它將同時處理保存/更新。此代碼未經測試,但將是一個好開始

0

第六點 - 謝謝。你的回答確實對我有幫助。

我改變了我的代碼中的一些變化,這裏是在EntriesController我admin_edit功能的一部分:

if ($this->request->is(array('post', 'put'))) { 

     //Load archive model and create object 
     $this->loadModel('Archive'); 
     $this->Archive->create(); 

     //Geting data of current entry (yes, i want to save old, non-edited entry data in archives) 
     $options = array('conditions' => array('Entry.' . $this->Entry->primaryKey => $id)); 
     $current_entry = $this->Entry->find('first', $options); 

     //assignment to request data of archive 
     $this->request->data['Archive'] = $current_entry['Entry']; 

     //adding id for foregin key 
     $this->request->data['Archive']['entry_id'] = $this->request->data['Entry']['id']; 
     //adding reason from form data 
     $this->request->data['Archive']['reason'] = $this->request->data['Entry']['reason']; 
     //remove id, new entry of archive will be added 
     unset($this->request->data['Archive']['id']); 

     // save archive 
     if ($this->Archive->save($this->request->data)) { 
      $this->Session->setFlash(__('The archive has been saved.')); 
     } else { 
      $this->Session->setFlash(__('The archive could not be saved. Please, try again.')); 
     } 

     // save edited entry 
     if ($this->Entry->save($this->request->data)) { 
      $this->Session->setFlash(__('The entry has been saved.')); 
      return $this->redirect(array('action' => 'index')); 
     } else { 
      $this->Session->setFlash(__('The entry could not be saved. Please, try again.')); 
     } 
    } 

現在我已經得到了我所需要的。我正在變老(編輯前)條目數據並將其保存爲存檔,具有原因。

相關問題