2014-10-12 43 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')); 
}