簡體   English   中英

CodeIgniter 4 - 如何在視圖中顯示 Flashdata?

[英]CodeIgniter 4 - How to display Flashdata inside a View?

我正在將我的項目從 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();

在 CodeIgniter 4 中設置 Flash 數據的新方法$session->setFlashdata('item', 'value'); 並查看$session->getFlashdata('item');

您可以在此處查看: 在 CodeIgniter 中的會話中設置 Flash 數據

我只是使用另一種方式來顯示 flashdata,它工作正常。

在我的控制器中,我為傳遞給視圖的數據添加了一個新索引:

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

您可以直接使用 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; ?>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM