Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access model from view in codeigniter?

can anyone tell me how do i access model from view in codeigniter?

like image 499
sonill Avatar asked Apr 27 '10 08:04

sonill


People also ask

How do you call a model function in view?

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.

How can you add or load a model in CodeIgniter?

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.

How do I make a ci3 model?

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() .


3 Answers

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?

like image 64
bschaeffer Avatar answered Oct 25 '22 02:10

bschaeffer


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 ...

like image 18
Ravi Soni Avatar answered Oct 25 '22 00:10

Ravi Soni


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.

like image 6
Sarfraz Avatar answered Oct 25 '22 00:10

Sarfraz