-
Notifications
You must be signed in to change notification settings - Fork 0
Display helper
[b]Introduction[/b]
I noticed my view files get confusing because of all the little checks that have to be made when displaying values. For example [code] // data array( array('start_date'=>'2008-01-01','total'=>'10'), array('start_date'=>'0000-00-00','total'=>'0') ); // view <?php foreach($rows as $row): ?>
<?php if($row['start_date'] != '0000-00-00') echo $row['start_date'] ?> <?php if($row['total'] != '0') echo $row['start_date'] ?> <?php endforeach ?> [/code] This is why i created the display helper.[b]Code[/b] The code is split up in two parts. There are constants and there is the display_helper.php file
The constants are added to the config/constants.php files and make it easier for you to change the default value where ever you used it. [code]
/* |
---|
Defaults |
----------------------------------------------------------------------- |
*/ |
define('DEFAULT_DATETIME', '0000-00-00 00:00:00'); |
define('DEFAULT_DATETIME_NO_SEC', '0000-00-00 00:00'); |
define('DEFAULT_DATE', '0000-00-00'); |
define('DEFAULT_TIME', '00:00:00'); |
define('DEFAULT_NUMBER', '0'); |
[/code] |
Add as many constants as you need. |
The display_helper.php file contain the functions used in the view file [code]
/* |
---|
show value if it's not the same as the default value |
---------------------------- |
*/ |
function display($value,$default) |
{ |
return ($value == $default)?'':$value;
}
/* |
---|
check if value is not the same as the default value |
---------------------------- |
*/ |
function is_default($value,$default) |
{ |
return ($value == $default)?TRUE:FALSE;
}
/* |
---|
show value or a formatted string with the value in it when the value exists |
---------------------------- |
*/ |
function display_isset($value,$str='') |
{ |
if( ! isset($value)) |
{ |
return '';
}
if($str != '') { return sprintf($str,$value); }
return $value; } [/code] It are only a few functions but they make view files a lot easier to read.
[b]Usage[/b] The example view code with the helper is [code] <?php foreach($rows as $row): ?>
<?php echo display($row['start_date'],'0000-00-00') ?> <?php echo display($row['total'],'0') ?> <?php endforeach ?> // or with the constants <?php foreach($rows as $row): ?> <?php echo display($row['start_date'],DEFAULT_DATE) ?> <?php echo display($row['total'],DEFAULT_NUMBER) ?> <?php endforeach ?> [/code]An example of the display_isset function [code] // without helper <p<?php if(isset($class)): ' class="'.$class.'"'; endif ?>>hello world
// with helper <p<?php echo display_isset($class,' class="%s"') ?>>hello world [/code]