清除CakePHP 3.1.1中的Flash消息

时间:2016-01-09 04:22:29

标签: cakephp-3.x

我正在尝试清除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消息的完整操作/表单。

然后,“完成”操作如下所示:

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(告诉他们“请完成您的客户资料数据。”)仍然会再次显示。 / p>

如果用户在视图上刷新,则两条Flash消息都会消失。

重定向时如何清除初始Flash消息?我尝试过使用clear键但似乎无法正常工作。

非常感谢任何建议! 谢谢, DBZ

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您可以在行动开始时添加此内容

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

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

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

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

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

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

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

答案 2 :(得分:0)

显然你将字符串传递给 clear 而不是布尔值:

3.1版中的新功能:添加了新的密钥清除功能。此键需要bool并允许您删除当前堆栈中的所有消息并启动一个新消息。

尝试设置 true 而不使用引号:

$this->Flash->set(__('Your customer information is complete and has been saved!'),[
    'clear'=> true
]);

答案 3 :(得分:0)

检查以确保您不会始终获得$completion == 0(也可能与FALSE匹配)。

我怀疑这就是您的Flash消息始终显示的原因。

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

答案 4 :(得分:0)

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

像这样使用:

$this->loadComponent( 'Flash', ['clear' => true] );