CodeIgniter Forums

Full Version: Help required getting logic out of View and in to Model
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]ashbyrich[/eluser]
I am trying to be a little bit more structured/keep garbage out of my views having been impressed by Freakauthor Light.

Crudely I want to create a summary list of the first 150 words of my 'content' field in the database. I could do something with php
Code:
substr(<?=$item->content ?>,0 ,150)
but would prefer a solution in my Model....

Controller (excerpt)
Code:
function index()
{

$data['heading'] = 'projects';
$this->load->model('Proj');
$data['query'] = $this->Proj->get_list();
$data['page'] = $this->config->item('FAL_template_dir').'template/projects';
$this->load->vars($data);
$this->load->view($this->_container);

}
Model (excerpt)
Code:
function get_list()
    {
    $query = $this->db->get('projects');
    return $query->result();
    }


View (excerpt)
Code:
<?php foreach($query as $item): ?>

<p> &lt;?=$item->id ?&gt; &lt;?=$item->content ?&gt;</p>

&lt;?php endforeach; ?&gt;

El Forum

[eluser]xwero[/eluser]
You can create a helper
Code:
function limit_text($text,$limit,$arraykey='')
{
    if(is_string($text))
    {
       return substr($text,0,$limit);
    }
  
    if(is_array($text) && $arraykey != '')
    {
        if(array_key_exists($arraykey,$text)) // for single dimension array
        {
           $text[$arraykey] = substr($text[$arraykey],0,$limit);
           return $text;
        }
        else // two dimensional array (database result)
        {
           foreach($text as $key => $item)
           {
               $text[$i][$arraykey] = substr($item[$arraykey],0,$limit);
           }
        }
    }
}
You can add the object branch if you want.

Then in the controller you can do
Code:
function index()
{

$data['heading'] = 'projects';
$this->load->model('Proj');
$this->load->helper('the helper name you put the function in');
$data['query'] = limit_text($this->Proj->get_list(),150,'content'); // in the get_list method you need to use result_array if you don't add a object branch in the function
$data['page'] = $this->config->item('FAL_template_dir').'template/projects';
$this->load->vars($data);
$this->load->view($this->_container);

}

El Forum

[eluser]ashbyrich[/eluser]
Many thanks for a really elegant solution to my problem...