0

我面临一个超过 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"。谁能告诉我哪里做错了?

4

1 回答 1

2

您没有将任何数据传递给您的视图。您可以使用第二个参数将数据传递给您的视图,而不是这样做

$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; ?>
于 2013-07-09T16:13:19.123 回答