I have a variable, contaning data that should be present in the entire site. Instead of passing this data to each view of each controller, I was wondering if there is a way to make this data available for every view in the site.
Pd. Storing this data as a session variable / ci session cookie is not an option.
Thanks so much.
A view is simply a web page, or a page fragment, like a header, footer, sidebar, etc. In fact, views can flexibly be embedded within other views (within other views, etc., etc.) if you need this type of hierarchy. Views are never called directly, they must be loaded by a controller.
call first controller from first view and pass form data to second view. On second view you can create hidden inputs and set their values from controller data. Now submit the second form to final controller and you will get all the values of both form. Hope this helps you.
Create a MY_Controller.php
file and save it inside the application/core folder. In it, something like:
class MY_Controller extends CI_Controller {
public $site_data;
function __construct() {
parent::__construct();
$this->site_data = array('key' => 'value');
}
}
Throughout your controllers, views, $this->site_data
is now available.
Note that for this to work, all your other controllers need to extend MY_Controller
instead of CI_Controller
.
You need to extend CI_Controller to create a Base Controller:
https://www.codeigniter.com/user_guide/general/core_classes.html
core/MY_Controller.php
<?php
class MY_Controller extend CI_Controller {
public function __construct() {
parent::__construct();
//get your data
$global_data = array('some_var'=>'some_data');
//Send the data into the current view
//http://ellislab.com/codeigniter/user-guide/libraries/loader.html
$this->load->vars($global_data);
}
}
controllers/welcome.php
class Welcome extend MY_Controller {
public function index() {
$this->load->view('welcome');
}
}
views/welcome.php
var_dump($some_var);
Note: to get this vars in your functions or controllers, you can use $this->load->get_var('some_var')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With