CodeIgniter Forums

Full Version: load model in view for header
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]bigtimslim[/eluser]
My site has a header that I want to print a random entry from a db table in. How would you tackle this? I tried just directly loading the model and printing the result and such in the header view, but am getting an error: "Call to a member function get_wally() on a non-object"

Code:
Model function:

function get_wally()
{
   $query = $this->db->query("SELECT wally_says FROM wally ORDER BY RAND() LIMIT 1");
   return $query->row();
}

from View:

<div id="wallysays" class="round">
   &lt;?php
       $this->load->model('Wally_model');
       $wally = $this->wally_model->get_wally();
       echo $wally->wally_says;
   ?&gt;
</div>


I must be doing something stupid here. Help me out? Smile

El Forum

[eluser]TheFuzzy0ne[/eluser]
Really, you shouldn't load/call models from within your view, although that's not the problem. You should also load your model using all lowercase characters, and ensure that your filename is also all lowercase.

El Forum

[eluser]bigtimslim[/eluser]
This is the first time I've tried loading a model in a view. I wouldn't normally, but it seems to me that the alternative is to do that in the constructor of every controller.. or is there a better way?

El Forum

[eluser]Armchair Samurai[/eluser]
Alternately, you could write a plugin, autoload it and then call it from your header. You could also extend the CI controller, load the data from the database in the constructor, store it either in a variable or set it as a config item, then call that from the header.

El Forum

[eluser]xwero[/eluser]
post_controller_constructor hook
Code:
function wally_says()
{
    $CI =& get_instance();
    $CI->load->model('wally_model','',true); // no need to autoload the database library
    $CI->load->vars(array('wally_says',$this->wally_model->wally_says()));
}
// wally_model.php
function wally_says()
{
   return $this->db->query("SELECT wally_says FROM wally ORDER BY RAND() LIMIT 1")->row()->wally_says; // php5
}
The wally_says function has one goal return a value from the wally_says field so why should your controller/view need to know which fieldname the value actually has?

El Forum

[eluser]bigtimslim[/eluser]
Thanks for the awesome comments guys. I will try to implement the xwero's approach. Way back when, I had read the hooks section of the documentation, but didn't really understand how/why I would use it. Now I do. Smile

El Forum

[eluser]Unknown[/eluser]
i'm new to codeigniter. i got the same problem, but i'm solved it just setting in my config file autoload.php just adding what model do you like to load, and you can call that model on every views.

i'm googlong this thread, hope this help other that look for an answer.


sorry for my english. english not my primary language.