How to check if the flash message set is empty in cakephp

1.5k views Asked by At

I have a login form and i am setting the flash message on invalid login like this in the controller:

$this->Session->setFlash(__('Invalid username or password'));

And displaying the message like below in ctp file :

<div id="error" >
<?php
echo $this->Session->flash();
?> 
</div>

CSS for the div is as follows:

    #error {
    padding:10px;
    display:inline-block;
    margin-right: 18px;
    font-size:16px;
    font-weight:600;
    position:relative;
    top:20px;
    }

When the page is loaded an empty flash message is shown. How to check if $this->Session->flash(); is empty and display div only if its not empty??

When the message is empty flash message on page load it looks like this:

When the message is empty flash message on page load it looks like this :

Similar way it looks like this when message is set:

Similar way it looks like this message is set:

1

There are 1 answers

1
Jacek B Budzynski On BEST ANSWER

Try this:

Create your Custom Elements with Error Alert, Success Alert, etc...

/View/Elements/error_alert.ctp

<!-- Example Bootstrap Error Alert -->
<div class="alert alert-danger">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    <strong><?php echo $message ?></strong>
</div>

/View/Elements/success_alert.ctp

<!-- Example Bootstrap Succes Alert -->
<div class="alert alert-success">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    <strong><?php echo $message ?></strong>
</div>

In your Views add this, It´s appear only when Message must be displayed

 <!-- It´s will work for all alert types (not only for error alerts) -->
<div class="col-md-12">
    <?php echo $this->Session->flash(); ?> 
</div>

if you want use one add this in your controllers:

For success Alert

$this->Session->setFlash('Success message!', 'success_alert');

For error Alert

$this->Session->setFlash('Error message!', 'error_alert');