如何将变量从控制器传递到视图

时间:2015-05-23 01:45:25

标签: php codeigniter

Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>

我在我的控制器中有这个代码。我想知道如何将global $wp_query; while ( have_posts() ) { the_post(); get_template_part('content', get_post_format()); echo $wp_query->current_post + 1; } 传递给我的HTML视图?

0

2 个答案:

答案 0 :(得分:0)

您没有在代码(控制器)中指定视图名称

根据:https://ellislab.com/codeigniter/user-guide/general/views.html

您必须使用:$ this-&gt; load-&gt; view(&#39; view_name&#39;,$ nameErr);

答案 1 :(得分:0)

试试这个

 // Don't Use $_POST[] use $this->input->post()

 $name = test_input($_POST["name"]); 

 // check if name only contains letters and whitespace

 if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
   $data['nameErr'] = "Only letters and white space allowed"; 
 }

 $this->load->view('view_name', $data);

要提交帖子,您需要 codeigniter form_validation Library您还可以使用我建议的回调函数。

控制器示例函数表单验证回调

class Login extends CI_Controller {

 function index() {

    $this->load->library('form_validation');

    $this->load->helper('form');
    $this->load->helper('url');

    $this->form_validation->set_rules('name', 'name', 'required|callback_checkname');

    if ($this->form_validation->run() == FALSE) {
        $this->load->view('your_view');
    } else {
        // redirect('success_page');
    }
 }

 function checkname() {

    $this->load->library('form_validation');

    $name = $this->input->post('name');

    if (preg_match("/^[a-zA-Z ]*$/", $name)) {
       $this->form_validation->set_message('checkname' ,"Only letters and white space allowed"); 
       return false;
    }
  }
}

查看示例

<?php echo validation_errors(); ?>
<form action="<?php echo base_url('login');?>" method="post">
<input type="text" name="name" />
<button type="submit">Submit</button>
</form>