CodeIgniter 4-如何在视图内显示Flashdata?

问题描述

我正在将我的项目从CodeIgniter 3升级到CodeIgniter 4, 我正在尝试在视图内显示flashdata消息,但不幸的是,我尝试的每种方法都出现了错误错误

在CodeIgniter 3中,我曾经这样称呼过:

<?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; ?>

我在CodeIgniter 4中尝试了相同的操作,但出现此错误

ErrorException
Undefined property: CodeIgniter\View\View::$session

有人可以告诉我如何实现这一目标吗? 预先感谢。

解决方法

上下文($ this)是View类的一个实例->您无权直接访问Session实例

您可以在下面创建新实例

$session = \Config\Services::session();
,

我只是使用另一种方式来显示Flash数据,而且效果很好。

在我的控制器中,我向传递给视图的数据添加了新索引:

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

然后在视图login.php中,我这样称呼它:

<?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; ?>

更新:

我只使用markAsFlashdata()方法,它运行完美。这是我在return方法之前在控制器中所做的事情:

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

然后在视图中,我使用$_SESSION['error']访问flashdata:

<?php if (isset($_SESSION['error'])): ?>
    <div class="alert alert-warning" role="alert">
        <?= $_SESSION['error']; ?>
    </div>
<?php endif;?>
,

在CodeIgniter 4中,设置Flash数据$session->setFlashdata('item','value');和查看$session->getFlashdata('item');的新方法

您可以在此处查看:Set Flash data in session in CodeIgniter

,

echo $this->section('content');之后添加此行

$session = \Config\Services::session(); 

<?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; ?>
,

您可以直接使用session()函数:

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