Masoud Motallebipour
Masoud Motallebipour

Reputation: 414

Calling a model in a Helper file using codeigniter

I want to write a function for loading dropdown in helper file and for that reason I want to Use my models in Helper file.

When I use this it give me the error:

$this->load->model("news_model");

The Error:

Fatal error: Using $this when not in object context in C:\xampp\test\application\helpers\component_helper.php on line 6

my method:

function dropdown($Class,$Attribute)
{
$Output=NULL;
$ClassName=$Class."_model";
$this->load->model($ClassName);
$FullData=$ClassName->get();
foreach ($FullData as $Data) 
{
    $Output.='<option value="'.$Data->Id.'">'.$Data->$Attribute.'</option>';
}
return $Output;
}

Thanks

Upvotes: 1

Views: 6267

Answers (3)

sravis
sravis

Reputation: 3680

Check this post:

function my_helper()
{
    // Get a reference to the controller object
    //$CI = get_instance();
    // use this below
    $CI = &get_instance();

    // You may need to load the model if it hasn't been pre-loaded
    $CI->load->model('my_model');

    // Call a function of the model
    $CI->my_model->do_something();
}

https://stackoverflow.com/a/2479485/1570901

Upvotes: 8

C06b
C06b

Reputation: 36

Here is the correction for you code:

function dropdown($Class,$Attribute)
{
$CI = get_instance();
$Output=NULL;
$ClassName=$Class."_model";
$CI->load->model($ClassName);
$FullData=$ClassName->get();
foreach ($FullData as $Data) 
{
    $Output.='<option value="'.$Data->Id.'">'.$Data->$Attribute.'</option>';
}
return $Output;
}

Now instead of using $this, always use $CI inside this method.

Hope this helps.

Upvotes: 1

DAG
DAG

Reputation: 6994

Helper functions are functions. This means they are not bound to an object nor class. $this is therefor not avaible!

You have to get the instance of CodeIgniter-Core from somewhere else!

CodeIgniter provides a get_instance(); function for that:

$CI = get_instance();

Now wereever you had $this->load etc. Replace $this with $CI to call on the CodeIgniter Core!

And by the way you are calling the model wrong. You have to access it via the CI-core:

 $CI->$Classname->get();

Upvotes: 3

Related Questions