2014-10-12 50 views
-1

我正在創建一個博客的基本教程。在刪除步驟,我有:刪除帖子時自定義setFlash()

public function delete($id){ 
    // if($this -> request -> is('get')){ 
    // throw new MethodNotAllowedException(); } 

    if ($this -> Post -> delete($id)) { 
     $this -> Session -> setFlash(
      __('The article %s was deleted', h($id)));//here is the line 
      return $this -> redirect(array('action' => 'index')); 
    } 

} 

我想的The article ID was deleted而不是讓The article TITLE was deleted;

我的問題是爲什麼下面的代碼在這種情況下不起作用?

__('The article %s was deleted', h($title))); 
+0

我曾經在任何地方見過h宣言?? – 2014-10-12 11:51:38

+2

您如何期待這種工作,在您的代碼中沒有任何名稱爲'title'的變量? – ndm 2014-10-12 12:02:58

+0

@AvinashBabu,沒有聲明。原文可以在這裏找到http://book.cakephp.org/2.0/en/getting-started.html#deleting-posts – ADDA 2014-10-12 12:11:20

回答

1
public function delete($id){ 
    // get the title 
    $this->Post->id = $id; 
    $title = $this->Post->field('title'); 

    // delete the record 
    if ($this->Post->delete($id)) { 
     $this->Session->setFlash(__('The article %s was deleted', h($title))); // output the title 
     return $this -> redirect(array('action' => 'index')); 
    } 

} 
0

因爲$id作爲參數傳遞給刪除函數傳遞。

我們可以在以下行中直接訪問它。

__('The article %s was deleted', h($id))); 

但是對於訪問其它字段從表中,你必須使用所傳遞的$id數據庫

去取。

如:

$title = $this->Post->field('title'); 

,然後使用它。

這是修改後的完整代碼。

public function delete($id){ 

$this->Post->id = $id; 
$title = $this->Post->field('title'); 


if ($this->Post->delete($id)) { 
    $this->Session->setFlash(__('The article %s was deleted', h($title))); 
    return $this -> redirect(array('action' => 'index')); 
}