function commerce_price_field_formatter_view in Commerce Core 7
Implements hook_field_formatter_view().
File
- modules/
price/ commerce_price.module, line 436 - Defines the Price field with widgets and formatters used to add prices with currency codes to various Commerce entities.
Code
function commerce_price_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$translated_instance = commerce_i18n_object('field_instance', $instance);
$element = array();
// Loop through each price value in this field.
foreach ($items as $delta => $item) {
// Do not render a price if the amount is NULL (i.e. non-zero empty value).
if (is_null($item['amount'])) {
// TODO: Consider if we should render as N/A or something indicating a
// price was not available as opposed to just leaving a blank.
continue;
}
// Theme the display of the price based on the display type.
switch ($display['type']) {
case 'commerce_price_raw_amount':
$element[$delta] = array(
'#markup' => check_plain($item['amount']),
);
break;
case 'commerce_price_formatted_amount':
$element[$delta] = array(
'#markup' => commerce_currency_format($item['amount'], $item['currency_code'], $entity),
);
break;
case 'commerce_price_formatted_components':
// Build an array of component display titles and their prices.
$components = array();
$weight = 0;
foreach ($item['data']['components'] as $key => $component) {
$component_type = commerce_price_component_type_load($component['name']);
// Initialize an empty component type array if the load failed.
if (!$component_type) {
$component_type = array(
'display_title' => '',
'weight' => NULL,
);
}
if (empty($components[$component['name']])) {
$components[$component['name']] = array(
'title' => check_plain($component_type['display_title']),
'price' => commerce_price_component_total($item, $component['name']),
'weight' => $component_type['weight'],
);
$weight = max($weight, $component_type['weight']);
}
}
// If there is only a single component and its price equals the field's,
// then remove it and just show the actual price amount.
if (count($components) == 1 && array_key_exists('base_price', $components)) {
$components = array();
}
// Add the actual field value to the array.
$components['commerce_price_formatted_amount'] = array(
'title' => check_plain($translated_instance['label']),
'price' => $item,
'weight' => $weight + 1,
);
// Allow other modules to alter the components.
drupal_alter('commerce_price_formatted_components', $components, $item, $entity);
// Sort the components by weight.
uasort($components, 'drupal_sort_weight');
// Format the prices for display.
foreach ($components as $key => &$component) {
$component['formatted_price'] = commerce_currency_format($component['price']['amount'], $component['price']['currency_code'], $entity);
}
$element[$delta] = array(
'#markup' => theme('commerce_price_formatted_components', array(
'components' => $components,
'price' => $item,
)),
);
break;
}
}
return $element;
}