10-13-2019, 02:58 AM
(10-12-2019, 08:03 AM)Digital_Wolf Wrote:(10-12-2019, 01:32 AM)jbloch Wrote: How to get session value in view file In CI4?Something like this:
PHP Code:// IN CONTROLLER:
<?php
namespace App\Controller;
use CodeIgniter\Controller;
class My_Controller extends Controller
{
private $session = null;
public function myMethod() {
$this->session = session();
$data['get_sess'] = $this->session->get('item');
echo view('folder/template', $data['get_session'])
}
}
// IN VIEWS:
<?= $get_session; ?>
Session documentation: Link
Hello,
You have 2 possibilities, it depends upon the number of variables of your session you want to transfer.
1. In the view code directly
The context ($this) is an instance of the View class --> you don't have access to the Session instance directly.
You have to write a bit of code in the View:
PHP Code:
$session = \Config\Services::session();
// then you use the way you want to retrieve the attribute you need (see the doc)
2. Controller code + view code
You can also pass the data during the call of the view() method in the Controller.
PHP Code:
<?php
namespace App\Controller;
use CodeIgniter\Controller;
class My_Controller extends Controller
{
protected $session = null; // use protected instead as recommended
public function myMethod() {
// We retrieve the Session class
$this->session = Services::session();
// We set some data
$this->session->item = 'Pouet';
// We pass (only) session data to the View
echo view('folder/template', $this->session->get());
// or:
//echo view('folder/template', ['item' => $this->session->get('item')]);
}
}
Then, in the view:
PHP Code:
<?= $item ?>
Should work

--
I prefer method 2, it is more about separating Controller and View from a purpose point of view.
Regards,