2013-11-14 120 views
0

我有一個Horse對象,它具有completed變量(文本)。我希望能夠在視圖中點擊set complete,然後將該馬的completed變量設置爲「是」。在此之後,我們會將用戶重定向到任務/索引。我的想法是在控制器中創建setcomplete($id)函數,所以我可以通過/setcomplete/4,那個馬的旗子會改變。更改AppController中的單個變量值

我已經爲它創建了一個基本視圖,但想法是我不需要視圖,但我不知道如何解決這個問題....我想使用$this->render()或者這種性質的東西。

這是基本代碼...傳入id然後更改變量,然後重定向到tasks/index。

我沒有收到錯誤....它只是不工作,就這樣。

public function setcomplete($id = null) { 
     if (!$this->Task->exists($id)) { 
      throw new NotFoundException(__('Invalid task')); 
     } 
     if ($this->request->is(array('post', 'put'))) { 
      $this->set('completed', 'yes'); 
      if ($this->Task->save($this->request->data)) { 
       $this->Session->setFlash(__('The task has been updated.')); 
       return $this->redirect(array('action' => 'index')); 
      } else { 
       $this->Session->setFlash(__('The task could not be saved. Please, try again.')); 
      } 
     } else { 

     } 

    } 
+0

你看到了什麼行爲?但是'$ this-> layout = $ this-> autoRender = false;'將阻止它拋出關於缺少視圖的錯誤。 – Kai

+0

即時看到沒有行爲...我設置了一個非常基本的視圖,它去那裏,但它並沒有改變變量,這是我想要它做的。 –

+0

您可以在執行保存的行上添加'debug($ this-> request-> data)'並在此處發佈結果嗎?可以幫助找出問題。 –

回答

1

根據我對你的問題的理解。你想爲Task模型設置completedyes。 我認爲你在這裏做錯了方式。

what about the $this->request->data here? 

是否包含要像結構的任務模型保存爲以下

Array(
    'Task' => Array(
     'id' => 4, // for eg.. 
     'completed' => 'yes' 
    ) 
) 

如果不是

你可以做這樣的解決問題的數據。 [假設你沒有$this->request->data]

public function setcomplete($id = null) { 
    if (!$this->Task->exists($id)) { 
     throw new NotFoundException(__('Invalid task')); 
    } 

    $this->Task->id = $id; 
    $this->Task->set('completed', 'yes') 

    if ($this->Task->save()) { 
     $this->Session->setFlash(__('The task has been updated.')); 
     return $this->redirect(array('action' => 'index')); 
    } else { 
     $this->Session->setFlash(__('The task could not be saved. Please, try again.')); 
    } 
} 
+0

這工作 - 我明白爲什麼現在。謝謝@Anil kumar! –

+0

很高興幫助:) –