2011-09-21 40 views
3

我使用CodeIgniter(2.03)是一个新手的问​​题,我有以下问题:代码点火器的问题:用传递变量视图

这里是我的主模板(视图):

<?php $this->load->view('backOffice/bo_header_in'); ?> 

<?php $this->load->view($bo_main_content); ?> 

<?php $this->load->view('backOffice/bo_footer_in'); ?> 

这里是我的模型:

<?php 

class Back_office_users extends CI_Model 
{ 

    public function getAllUsers() 
    { 
    $query = $this->db->query("SELECT * FROM users"); 

    if ($query->num_rows() > 0) { 
     foreach ($query->result() as $rows) { 
     $users[] = $rows; 
     } 
     return $users; 
    } 
    } 
} 

这里是我的CONTROLER:

<?php 

class Dashboard extends CI_Controller 
{ 

    public function __construct() 
    { 
    parent::__construct(); 
    $this->is_logged_in(); 
    } 

    public function index() 
    { 
    $this->load->model('back_office_users'); 
    $users['rows'] = $this->back_office_users->getAllUsers(); 

    $data['bo_main_content'] = "backOffice/dashboard"; 

    $this->load->view('backOffice/bo_template_in', $data, $users); 

    // if I pass the variable like this it works just fine... 
    //$this->load->view('backOffice/users', $users); 
    } 

    public function is_logged_in() 
    { 
    $is_logged_in = $this->session->userdata('is_logged_in'); 
    if (!isset($is_logged_in) || ($is_logged_in != true)) { 
     $this->accessdenied(); 
    } 
    } 

    public function accessdenied() 
    {  
    $data['bo_main_content'] = 'backOffice/accessdenied'; 
    $this->load->view('backOffice/bo_template', $data); 
    } 

    public function logout() 
    {  
    $this->session->sess_destroy(); 
    redirect('backOffice/index'); 
    } 
} 

而且仪表板视图是这样的:

<?php 
    print_r($users); 
?> 

我收到以下错误:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: users

Filename: backOffice/dashboard.php

Line Number: 9

任何人都可以提供一些线索我怎么能解决这个问题?我不使用模板创建另一个视图,并打印数组。

回答

3

您没有将$users变量传递给第二个(嵌套)视图。

我建议在$data数组中添加$users,然后在第一个视图中将$users数组传递给嵌入视图。所以,在你的控制器:

public function index() { 

    /* stuff... */ 

    $data['users']['rows'] = $this->back_office_users->getAllUsers(); 

    $data['bo_main_content'] = "backOffice/dashboard"; 

    /* stuff... */ 

    $this->load->view('backOffice/bo_template_in', $data); 
} 

然后在主视图:

<?php $this->load->view($bo_main_content, $users); ?> 

然后在仪表板视图:

<?php 
    print_r($rows); 
?> 

这是因为在主视图,如你所知,CodeIgniter将$data的所有元素都转换为变量,所以我们最终会得到$users变量。 $users是一个包含rows的数组,因此当我们将$users传递给第二个视图时,第二个视图将所有元素$users转换为查看变量,因此我们现在可以访问$row

+0

谢谢亚历克斯。 不仅代码的作品,但从你的答案,我意识到我的错误。 感谢您的时间和分享您宝贵的知识。 问候,Zoreli – Zoran

相关问题