Welcome Guest, Not a member yet? Register   Sign In
Methods in a model to manipulate attributes
#1

[eluser]Unknown[/eluser]
A very good day to all!

I've just started using codeigniter, loving it so far. The only thing I just can't seem to figure out is how to use a method in a model to manipulate an attribute.

Let's say I handle my news items (in a database) with the News_model. It has a date_posted, title and content field. I save the date as a unix_timestamp.

In a view, when looping through an array of found objects, you can just call on fields by using $row->fieldname;

Code:
foreach($items as $news_item):
echo $news_item->date_posted;
endforeach;

The above would simply echo the unix timestamp. You can just use the mdate function (amongst others) in the view, but that can be quite cumbersome when you have to repeat it in multiple views. Is there a way to use a method (in the model) to manipulate one of these fields without having to do it everywhere (for example in every view using that field), so for example if I want the date (unix) to display human readable, like 02-22-2011, with a method like "show_date()"? I expected something like this to work:

Code:
echo $news_item->display_date();

I would imagine my model looking something like this:

Code:
class News_model extends CI_Model {
  function __construct()
  {
    parent::__construct();
  }
  function get_all()
  {
    // do some database fetching
  }
  function display_date()
  {
    return mdate("%m-%d-%Y", $this->date_posted);
  }


Looking forward to resolving this issue, I love codeigniter!

edit: think I might've posted in the wrong forum, sorry!
#2

[eluser]InsiteFX[/eluser]
Maybe something like this:
Code:
class News_model extends CI_Model {

    // not needed if not being used!
    function __construct()
    {
        parent::__construct();
    }

    function get_all()
    {
        $data = array();

        // do some database fetching

        if ($query->num_rows() > 0)
        {
            foreach ($query->result() as $row)
            {
                $data['title'] = $row->title;
                $data['name']  = $row->name;
                $data['date']  = $this->display_date($row->date);
                $data['body']  = $row->body;
            }
        }
        
        return $data;
    }

    function display_date($value)
    {
        return mdate("%m-%d-%Y", $value);
    }
}

InsiteFX




Theme © iAndrew 2016 - Forum software by © MyBB