2015-04-05 59 views
0

我对codeigniter很陌生,我正在构建一些示例工具来了解我的解决方法。我已经在网上关注了一些基本的教程,现在我要走自己的路了。在codeigniter中访问来自控制器的发布变量

我有下面的代码,我试图解决,如果用户存在之前注册他们。我也无法知道如何告诉我的观点,即如果用户已经存在错误,我会在哪里传回数据?

我得到的错误是:

致命错误:使用$这在不在线的/Users/Tom/www/crm/application/helpers/site_helper.php对象上下文18

控制器/ users.php

public function register() 
    { 
     $this->load->helper('form'); 
     $this->load->library('form_validation'); 

     $data['title'] = 'Create a new user'; 

     $this->form_validation->set_rules('firstname', 'First Name', 'required'); 
     $this->form_validation->set_rules('surname', 'Surname', 'required'); 

     if ($this->form_validation->run() === FALSE) 
     { 
      $this->load->view('templates/header', $data); 
      $this->load->view('users/register'); 
      $this->load->view('templates/footer'); 

     } 
     else 
     { 
      if(c_userexists($this->input->post('email'))){ 
       $this->load->view('templates/header', $data); 
       $this->load->view('users/register'); 
       $this->load->view('templates/footer'); 
      } else { 
       $this->users_model->set_register(); 
       $this->load->view('users/success'); 
      } 
     } 
    } 

助手/ site_helper.php

if(!function_exists('c_userexists')) 
    { 
     function c_userexists($value) 
     { 
      $this->db->select('count(*) as user_count'); 
      $this->db->from('users'); 
      $this->db->where('email', $userId); 

      $query = $this->db->get(); 
      if($query > 0){ 
       return true; 
      } else { 
       return false; 
      } 
     } 
    } 

模型/ Users_model.php

public function set_register() 
    { 
     $this->load->helper('url'); 

     $data = array(
      'firstname' => $this->input->post('firstname'), 
      'surname' => $this->input->post('surname'), 
      'email' => $this->input->post('email'), 
      'password' => c_passencode($this->input->post('email')) 
     ); 

     return $this->db->insert('users', $data); 
    } 
+0

看看这篇文章帮助:http://stackoverflow.com/questions/ 6234159/codeigniter-cant-access-this-within-function-in-view这是一个视图,而不是帮助器,但同样的问题。 – 2015-04-05 18:38:10

回答

0

$this是到控制器对象实例的引用。你不能直接在助手功能中引用$this。您可以使用帮助函数get_instance来访问当前正在运行的控制器实例的实例。

为了使长话短说,更新您的site_helper:

if(!function_exists('c_userexists')) 
{ 
    function c_userexists($value) 
    { 
     $CI =& get_instance(); 
     $CI->db->select('count(*) as user_count'); 
     $CI->db->from('users'); 
     $CI->db->where('email', $userId); 

     $query = $CI->db->get(); 
     if($query > 0){ 
      return true; 
     } else { 
      return false; 
     } 
    } 
} 

欲了解更多信息,请访问: http://www.codeigniter.com/userguide3/general/ancillary_classes.html?highlight=get_instance#get_instance