Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data available for all views in codeigniter

Tags:

codeigniter

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.

like image 972
user1739460 Avatar asked Apr 23 '13 13:04

user1739460


People also ask

What is the use of views in CodeIgniter?

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.

How pass data from one page to another in CodeIgniter?

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.


2 Answers

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_datais now available. Note that for this to work, all your other controllers need to extend MY_Controllerinstead of CI_Controller.

like image 75
Mudshark Avatar answered Oct 02 '22 17:10

Mudshark


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')

like image 30
Aurel Avatar answered Oct 02 '22 17:10

Aurel