Custom global CakePHP function

In the application in which I work, there are several database fields called "active", which is logical. However, instead of displaying "1" or "0" in the views, I would like to say "Yes" or "No."

I have the following function:

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

However, I'm not sure where I should put this global function? Will it be the app_model.php file? Also, how can I call this function to apply β€œformatting”?

+4
source share
2 answers

You must leave the data coming from the database until you need to display it. This means that View is the right place to change it. I would just go with a simple one:

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

But if you need more complex formatting rules that you don't want to repeat every time, create a custom helper.

You can define a global function in bootstrap.php , but I would not recommend it.

+5
source

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

 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; } } 

Thus, you still have all the fields, if the form is normal, and you can, for example, update and save your model, which does not work if you change the int value obtained from db to a string.

0
source

All Articles