Skip to content
Advertisement

CodeIgniter 4 – How to display Flashdata inside a View?

I’m upgrading my project from CodeIgniter 3 to CodeIgniter 4, I’m trying to display a flashdata message inside a view but unfortunately I get differents error for each method I try.

In CodeIgniter 3, I used to call something like:

<?php if ($this->session->flashdata('message')) : ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?php echo $this->session->flashdata('message'); ?>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    </div>
<?php endif; ?>

I try the same in CodeIgniter 4 but I get this error:

ErrorException
Undefined property: CodeIgniterViewView::$session

Can any one show me how to achieve this ? Thanks in advance.

Advertisement

Answer

I just use another way to display a flashdata and it works fine.

In my controller, I added a new index to the data passed to the view:

$data['message'] = "Sorry, you must login first";
return view('login', $data);

Then in the view login.php I call it like this:

<?php if (isset($message)) : ?>
    <div class="alert alert-warning alert-dismissible fade show" role="alert">
        <?php echo $message; ?>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    </div>
<?php endif; ?>

UPDATE:

I just use the markAsFlashdata() method and It works perfectly. Here’s what I did in the controller just before the return method:

$_SESSION['error'] = 'Sorry, you must login first';
$session = session();
$session->markAsFlashdata('error');

Then in the view I access the flashdata using $_SESSION['error']:

<?php if (isset($_SESSION['error'])): ?>
    <div class="alert alert-warning" role="alert">
        <?= $_SESSION['error']; ?>
    </div>
<?php endif;?>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement