I have a index view returning a table from a specific model. Within this table shown in the index view, i intend to display icons based on the entry of a database field (e.g., the database field is '0', the icon shall be glyphicon-remove, when it is '1' it shall be glyphicon-ok). What is the best approach to follow the MVC idea and DRY? Shall the logic (assigning the icon based on the value) be placed in the index function of the controller or is it better to have the logic in the corresponding view (or even in the model)?
What is the best approach to follow the MVC idea and DRY?
A helper. Clearly not the controller.
I've written a helper method called bool() for that task.
/**
* Bool
*
* @param mixed $value
* @param array $options
* @return string
*/
public function bool($value, $options = array()) {
$defaults = array(
'true' => __d('app', 'Yes'),
'false' => __d('app', 'No'),
'escape' => true,
);
$options = Hash::merge($defaults, $options);
$return = $options['false'];
if ($value == true) {
$return = $options['true'];
}
if ($options['escape'] === true) {
return h($return);
}
return $return;
}
Then use it:
$this->MyHelper->bool($yourValue, [
'true' => 'glyphicon glyphicon-ok',
'false' => 'glyphicon glyphicon-remove']
);
Depending on the task it might be better to write another helper method that uses bool() to do the check but to output your whole string, whatever you want to render. You didn't shown any code, so it's just a guess.