function fraction_field_formatter_view in Fraction 7
Implements hook_field_formatter_view().
File
- ./
fraction.field.inc, line 423 - Fraction Field API functions
Code
function fraction_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$settings = $display['settings'];
$element = array();
// Iterate through the items.
foreach ($items as $delta => $item) {
// Start with empty output.
$output = '';
// Merge the item with default values, in case it's empty.
$defaults = array(
'numerator' => 0,
'denominator' => 1,
);
$item = array_merge($defaults, $item);
// Build output based on display type.
switch ($display['type']) {
// This formatter simply outputs the field as a fraction ([numerator]/[denominator]).
case 'fraction_default':
$output = fraction($item['numerator'], $item['denominator'])
->toString(field_filter_xss($settings['separator']));
break;
// This formatter outputs the field as a decimal value with a fixed or automatic precision.
case 'fraction_decimal':
$auto_precision = !empty($settings['auto_precision']) ? TRUE : FALSE;
$output = fraction($item['numerator'], $item['denominator'])
->toDecimal($settings['precision'], $auto_precision);
break;
case 'fraction_percentage':
$output = fraction($item['numerator'], $item['denominator'])
->multiply(fraction_from_decimal('100'))
->toDecimal($settings['precision'], !empty($settings['auto_precision'])) . '%';
break;
}
// Add prefix and suffix, if desired.
if ($settings['prefix_suffix']) {
$prefixes = isset($instance['settings']['prefix']) ? array_map('field_filter_xss', explode('|', $instance['settings']['prefix'])) : array(
'',
);
$suffixes = isset($instance['settings']['suffix']) ? array_map('field_filter_xss', explode('|', $instance['settings']['suffix'])) : array(
'',
);
$prefix = count($prefixes) > 1 ? format_plural($item['value'], $prefixes[0], $prefixes[1]) : $prefixes[0];
$suffix = count($suffixes) > 1 ? format_plural($item['value'], $suffixes[0], $suffixes[1]) : $suffixes[0];
$output = $prefix . $output . $suffix;
}
// Create the markup element.
$element[$delta] = array(
'#type' => 'markup',
'#markup' => $output,
);
}
return $element;
}