florian
florian

Reputation: 3

Display icon based on database entry

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)?

Upvotes: 0

Views: 537

Answers (2)

floriank
floriank

Reputation: 25698

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.

Upvotes: 1

Sumon Sarker
Sumon Sarker

Reputation: 2795

You can do it using different ways. Like

  • Storing glyphicon icons classes to database field
  • Set glyphicon classes to an Array and display it with your conditions
  • Set conditions, When displaying data in View[HTML]

EXAMPLE [In View]

$data = array(/*YOUR QUERY DATA IS HERE*/);

foreach ($data as $key => $value) { /*Check your Database field is `0` or `1`*/
    $icon = 'glyphicon glyphicon-remove';

    if ($value->YOUR_FIELD==1) { /*Check with your proper field name*/
      $icon = 'glyphicon glyphicon-ok'
    }

    echo "<span class='{$icon}'></span>";
}

Upvotes: 0

Related Questions