问题描述
我面临有线问题超过2小时。我想不出来。我试图传递变量errors
从模型到视图,但是当我尝试加载页面时显示错误,说明未定义的变量:errors
。我试图建立一个注册页面注册新用户。
这是寄存器的控制器
I am facing a wired problem for more than 2 hours. I couldn't figured it out. I am trying to pass the variable "errors"
from model to view but when I try to load the page it shows error saying "undefined variable: errors"
. I am trying to build a "register" page for registering new users. Here is my controller for register
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']数组。
下面的视图
In above when there is a error in validation I set the error in $data['errors'] array. The view is given below
<h2>Register User</h2>
<?php if($errors): ?>
<div style="background:red;color:white;">
<?php echo $errors; ?>
</div>
<?php endif; ?>
但是当我在浏览器上打开注册页面时,会显示错误: 未定义的变量:errors
。任何人都可以告诉我我在哪里做错了?
But when I open the register page on browser, it shows the error saying "Undefined variable: errors"
. Can anyone tell me where I have done wrong?
推荐答案
您可以使用第2个参数将数据传递到视图,而不是执行
You are not passing any data to your views. You can use the 2nd parameter to pass data to your views so rather than doing
$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);
然后当你在你的观点,你可以做
Then when you are in your view you can do
<h2>Register User</h2>
<?php if($errors): ?>
<div style="background:red;color:white;">
<?php echo $errors; ?>
</div>
<?php endif; ?>
这篇关于将数据从控制器传递到Codeigniter的视图时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!