Search code examples
phpcodeignitercodeigniter-2

Including view file in codeigniter


I am a newbie in Codeigniter. I am doing a project in which in every pages, I would like to include a drop down for showing multi-languages. For this, I am including a view file in one of the view file in another controller as:

<?php $this->load->view('language/alllang');?>

In alllang.php, I would like to include the code for displaying drop down. For this I have created a controller LanguageController with the following code:

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Language extends CI_Controller
{

    function __construct()
    {
        parent::__construct();

        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
    }


    function alllang()
    { 
        $data['val']="hhh";  // for testing
        $this->load->view('alllang',$data);
        exit;
    }
}

Code for alllang.php is:

<?php
echo $val;
?>

But I am getting an error like this:

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: val
Filename: language/alllang.php
Line Number: 2

This code is only for testing purpose (not the code for multilanguage). How can I set the value to be included in view file from controller.


Solution

  • Edited for database access functionality:

    You could just create a library file and save it in application/libraries, call it "language_lib.php":

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    class Language_lib{
        function __construct(){
            $this->CI =& get_instance();
        }
    
        function lang_dropdown(){
            //db queries:
            $q = $this->CI->db->select('*')->from('table')->get()->result_array();
            $html = … //your dropdown code here using $q
            return $html;
        }
    }
    

    Next, in application/config/autoload.php:

    $autoload['libraries'] = array('language_lib');
    

    Now in each controller method that needs the drop down, e.g. the index method:

    function index(){
        $data['dropdown'] = $this->language_lib->lang_dropdown();
        $this->load->view('some_view', $data);
    }
    

    You can access this in the view with <?php echo $dropdown; ?>