1

我正在尝试清除 CakePHP 3.1.1 中的 Flash 消息

当用户登录时,我有一个功能,如果他的客户数据不完整,他会被重定向到一个表单来完成它。看起来像这样:

public function index()
{   
    //Some code to check whether the customers profile is complete

    //If it's not complete, then redirect to the "complete" action with a flash message
    if($completion == 0){
       $this->Flash->success(__('Please complete your customer profile data.'));
        $this->setAction('complete', $custid);

    //Otherwise go to their view 
    } elseif ($completion == 1){
        $this->setAction('view', $custid);
    } 
}

这很好用,并且用户被重定向到带有 Flash 消息的完整操作/表单。

然后 Complete 操作如下所示:

public function complete($id = null)
{  
    //Get all the customer data input

    if ($this->request->is(['patch', 'post', 'put'])) {
        $customer = $this->Customers->patchEntity($customer, $this->request->data);
        //Set the completion status to complete (1)
        $customer->completion_status = 1;
        if ($this->Customers->save($customer)) {
            $completion = 1;
            $this->set('completion', $completion);

        //After the Save, redirect to the View action with a new Flash Message
            $this->Flash->set(__('Your customer information is complete and has been saved!',['clear'=>'true']));
            return $this->redirect(['action' => 'view',$custid]);
        } else {
            $this->Flash->error(__('The customer could not be saved. Please, try again.'));
        }
    }
    $this->set(compact('customer'));
    $this->set('_serialize', ['customer']);
}

它工作正常但是:当用户在保存数据后被重定向到带有 Success Flash 的 View 操作时,索引中的 Flash(告诉他们“请完成您的客户资料数据。”)仍然会再次出现。

如果用户在视图上刷新,那么两条 Flash 消息都会按原样消失。

重定向时如何清除该初始 Flash 消息?我试过使用清除键,但它似乎不起作用。

任何意见是极大的赞赏!谢谢, DBZ

4

5 回答 5

2

您可以在操作开始时添加它

$this->request->session()->delete('Flash');

要删除更具体的内容,您可以执行例如仅删除来自 AuthComponent 的消息

$this->request->session()->delete('Flash.auth');

还有一件事:您可以处理视图中显示的 Flash 消息,例如:

this->Flash->render('auth');

或者

this->Flash->render('error');

如果您不显示它保留在会话中的闪存消息,直到您将其显示在某处或将其从会话中删除。

于 2016-12-02T11:38:02.747 回答
1

Flash消息存储在会话中,因此只需清除相关的会话密钥:$this->Session->delete('Flash.flash')$this->Session->delete('Flash')

于 2016-01-09T07:03:24.023 回答
0

3.1 版中的新功能:Flash 消息现在可以堆叠。使用相同键连续调用 set() 或 __call() 会将消息附加到 $_SESSION 中。如果您想保留旧的行为(即使在连续调用之后也有一条消息),请在配置组件时将 clear 参数设置为 true。

像这样使用:

$this->loadComponent( 'Flash', ['clear' => true] );
于 2016-08-12T06:41:10.097 回答
0

检查以确保您并不总是得到$completion == 0(也可以匹配FALSE)。

我怀疑这就是为什么您的 Flash 消息总是显示的原因。

Cake 会在显示后自动删除一条 flash 消息。

于 2016-01-16T06:36:26.773 回答
0

显然你正在传递一个字符串来清除而不是一个布尔值:

3.1 版中的新功能:添加了新的密钥清除。该键需要一个布尔值,并允许您删除当前堆栈中的所有消息并开始一个新消息。

尝试在不带引号的情况下设置true :

$this->Flash->set(__('Your customer information is complete and has been saved!'),[
    'clear'=> true
]);
于 2016-01-14T18:25:18.293 回答