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.

有帮助吗?

解决方案

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

其他提示

Your explanation is a bit confusing, but by doing this

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

You're not calling a controller, you're calling a view only, without passing any data. If I get it right, you have a parent view, then inside it you'd like to call a language drop down view? Well, in this case a drop down view should be called with data array, and data should be coming from controller calling a parent view. Does it make sense?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top