Search code examples
cakephpflash-message

How to give Flash message a custom css class in cake 3


I want to give a Flash message a custom css class in Cakephp 3, there is my function in my (edit in this case) controller:

public function edit($id = null)
{
    $this->viewBuilder()->layout('personalizado');
    $user = $this->Users->get($id, [
        'contain' => []
    ]);
    if ($this->request->is(['patch', 'post', 'put'])) {
        $user = $this->Users->patchEntity($user, $this->request->data);
        if ($this->Users->save($user)) {
            $this->Flash->success('Utilizador editado com sucesso.', 'default', ['class' => 'alert alert-success']);
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('Erro ao apagar utilizador, por favor tente de novo.'));
        }
    }
    $this->set(compact('user'));
    $this->set('_serialize', ['user']);
}

I added the custom css claas in this line:

$this->Flash->success('Utilizador editado com sucesso.', 'default', ['class' => 'alert alert-success']);

but is not working, thanks in advance.


Solution

  • // In your Controller
    $this->Flash->success('The user has been saved', [
        'params' => [
            'class' => 'alert alert-success'
        ]
    ]);
    
    // In your View
    <?= $this->Flash->render() ?>
    
    <!-- In src/Template/Element/Flash/success.ctp -->
    <div class="<?= h($params['class']) ?>">
        <?= h($message) ?>
    </div>