将数据从控制器传递到Codeigniter视图时出错

时间:2013-07-09 15:57:33

标签: codeigniter

我遇到有线问题超过2小时。我无法理解。我试图将变量"errors"从模型传递到视图,但是当我尝试加载页面时,它显示错误"undefined variable: errors"。我正在尝试构建一个用于注册新用户的“注册”页面。 这是我的注册控制器

function register(){
    if($_POST){
        $config = array(
            array(
                'field' => 'username',
                'label' => 'Username',
                'rules' => 'trim|required|min_length[3]|is_unique[users.username]'
            ),
            array(
                'field' => 'password',
                'label' => 'Password',
                'rules' => 'trim|required|min_length[5]'
            ),
            array(
                'field' => 'password2',
                'label' => 'Password Confirm',
                'rules' => 'trim|required|min_length[5]|matches[password]'
            ),
            array(
                'field' => 'user_type',
                'label' => 'User Type',
                'rules' => 'required'
            ),
            array(
                'field' => 'email',
                'label' => 'Email',
                'rules' => 'trim|required|is_unique[users.email]|valid_email'
            )
        );
        $this->load->library('form_validation');
        $this->form_validation->set_rules($config);
        if($this->form_validation->run() == FALSE){
            $data['errors'] = validation_errors();
        }else{
            $data_array = array(
                'username' => $_POST['username'],
                'password' => sha1($_POST['password']),
                'email' => $_POST['email'],
                'user_type' => $_POST['user_type']
            );
            $this->load->model('user');
            $userid = $this->user->create_user($data_array);
            $this->session->set_userdata('userID', $userid);
            $this->session->set_userdata('user_type',$_POST['user_type']);
            redirect(base_url().'index.php/posts');
        }
    }
    $this->load->helper('form');
    $this->load->view('header');
    $this->load->view('register_user');
    $this->load->view('footer');
}

在上面,当验证出错时,我在$ data ['errors']数组中设置了错误。 视图如下:

<h2>Register User</h2>
<?php if($errors): ?>
<div style="background:red;color:white;">
<?php echo $errors; ?>
</div>
<?php endif; ?>

但是当我在浏览器上打开注册页面时,会显示错误"Undefined variable: errors"。谁能告诉我哪里做错了?

1 个答案:

答案 0 :(得分:3)

您没有将任何数据传递给您的观看次数。您可以使用第二个参数将数据传递给视图,而不是执行

$this->load->view('header');
$this->load->view('register_user');
$this->load->view('footer');

你想做

$aData['errors']
$this->load->view('header', $aData);
$this->load->view('register_user', $aData);
$this->load->view('footer', $aData);

然后当你在你的视野中时,你可以做到

<h2>Register User</h2>
<?php if($errors): ?>
    <div style="background:red;color:white;">
        <?php echo $errors; ?>
    </div>
<?php endif; ?>