删除帖子时自定义setFlash()

时间:2014-10-12 11:49:34

标签: php cakephp

我正在阅读他们创建博客的基本教程。在删除步骤我有:

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)));

2 个答案:

答案 0 :(得分: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'));
     }

}

答案 1 :(得分: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'));
 }