can anyone tell me how do i access model from view in codeigniter?
CodeIgniter ApproachCreate a Model to query through the database and return the data (as an array or object) Create a Controller to load and fetch the result from the Model (a method of the Model), and pass the returned data to the view. Create a View and use PHP loops to echo the result out, build the HTML.
Auto-loading Models If you find that you need a particular model globally throughout your application, you can tell CodeIgniter to auto-load it during system initialization. This is done by opening the application/config/autoload. php file and adding the model to the autoload array.
Syntax (call model method) –$this->[Model-class-name]->method-name(); Create a User. php file in application/controllers directory. Load above created Main_model using $this->load->model('Main_model') method in the __construct() method and call getUsers() method using $this->Main_model->getUsers() .
CodeIgniter's $this->load->model()
returns absolutely nothing. Look at it: system/libraries/Loader.php
.
This will output absolutely nothing:
$model = $this->load->model('table');
print_r($model);
And this next example will give you the fatal error Call to a member function some_func() on a non-object
:
$model = $this->load->model('table');
$model->some_func();
It doesn't matter whether that function even exists, $model
is not an object.
The thing to do is have a method in your model that returns data, then call that function and pass the results to your view file:
$this->load->model('table');
$data = $this->table->some_func();
$this->load->view('view', $data);
PS: How is the only answer you've accepted the absolute wrong thing to do?
Load a model on the controller
$this->load->model('yourmodel');
Assign this model to a var like this
$data['model_obj'] = $this->yourmodel;
and assign this data array to your view template
Use $model_obj object on the view template for calling model methods
$model_obj->some_method()
Hope this helps ...
See the thread:
View Calling a Model
By the way why do you need to access the model
from the view
, you can send the model data to the view from the controller
too which is the usual and better approach.
As a good note, keep your processing logic out of the view, you should use controller
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With