tags:

views:

674

answers:

2

The application I am working on have several database fields called "active", which is boolean. However, instead of displaying "1" or "0" in views, I would like it to say "Yes" or "No".

I have the following function:

function activeFriendlyName($status)
    {
     if ($status == 1)
     {
      return "Yes";
     }
     else
     {
      return "No";
     }
    }

However, I am unsure where I should put this global function? Would it be the app_model.php file? In addition, how would I call this function to apply the "formatting"?

+2  A: 

You should leave the data coming from the database as is until you need to display it. That means the View is the right place to change it. I'd just go with a simple:

echo $model['Model']['bool'] ? "Yes" : "No";

But if you need more complex formating rules that you don't want to repeat every time, make a custom Helper.

You could define a global function in bootstrap.php, but I wouldn't recommend it.

deceze
That's how I have it setup right now: hard-coded. I was trying to setup a way so if I decided to say "Active" : "Not Active" it would be easier to change globally.....
Jefe
Then the best option is to make a custom helper. Or use the translation functions: `$x ? __('Yes') : __('No')`
deceze
Or echo a `constant`, that you define in `bootstrap.php`.
deceze
@deceze I forgot about helpers. I'll give that a try :)
Jefe
A: 

What I would personally do is to add an afterFind callback to the models that you with to change status in.

class MyModel extends Model {

    ... // the rest of model code

    function afterFind($results) {
        foreach ($results as $key => $val) {
            if (isset($val['MyModel']['status'])) {
                $results[$key]['MyModel']['status_text'] = $results[$key]['MyModel']['status'] ? 'Yes' : 'No';
            }
        }
        return $results;
    }
}

This way you still have all the fields if normal form and you can still for example update and save your model which woudn't work if you change the int value fetched from the db to string.

RaYell
Not a good idea. Not only does it take more time to do every query, you're also littering your results with more data. If you ever decide to create a "`status_text`" field in your model you're in big trouble.
deceze
No you won't. As you may have noticed I added an extra field to the model called `status_text`. I'm not modifying the original value.
RaYell
Sorry, misread, fixed earlier comment.
deceze