You are here

commerce_price.module in Commerce Core 8.2

Same filename and directory in other branches
  1. 7 modules/price/commerce_price.module

Defines the Currency entity and the Price field.

File

modules/price/commerce_price.module
View source
<?php

/**
 * @file
 * Defines the Currency entity and the Price field.
 */
use Drupal\commerce_price\Plugin\Field\FieldFormatter\PriceCalculatedFormatter;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\views\Plugin\views\field\EntityField;

/**
 * Implements hook_theme().
 */
function commerce_price_theme() {
  return [
    'commerce_price_plain' => [
      'variables' => [
        'number' => 0,
        'currency' => NULL,
      ],
      'template' => 'commerce-price-plain',
    ],
    'commerce_price_calculated' => [
      'variables' => [
        'calculated_price' => NULL,
        'purchasable_entity' => NULL,
      ],
    ],
  ];
}

/**
 * Implements hook_ENTITY_TYPE_insert() for 'configurable_language'.
 */
function commerce_price_configurable_language_insert(ConfigurableLanguage $language) {
  if (!\Drupal::isConfigSyncing()) {

    // Import currency translations for the new language.
    $importer = \Drupal::service('commerce_price.currency_importer');
    $importer
      ->importTranslations([
      $language
        ->getId(),
    ]);
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Removes the "Calculated price" formatter from views field options, if
 * it is not applicable. Since the formatter is product variation specific,
 * this prevents it from accidentally being used on other entity types.
 *
 * @todo Remove when https://www.drupal.org/node/2991660 gets fixed.
 */
function commerce_price_form_views_ui_config_item_form_alter(&$form, FormStateInterface $form_state) {

  /** @var \Drupal\views\Plugin\views\field\EntityField $handler */
  $handler = $form_state
    ->get('handler');
  if ($handler instanceof EntityField && !empty($handler->definition['entity_type'])) {
    $entity_type_id = $handler->definition['entity_type'];
    $field_name = $handler->definition['field_name'];

    /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager */
    $field_manager = \Drupal::service('entity_field.manager');
    $field_definitions = $field_manager
      ->getFieldStorageDefinitions($entity_type_id);
    $field_definition = $field_definitions[$field_name] ?? NULL;
    if (!$field_definition || $field_definition
      ->getType() != 'commerce_price') {
      return;
    }

    // Remove the formatter from configurable fields, and non-applicable ones.
    if (!$field_definition instanceof BaseFieldDefinition || !PriceCalculatedFormatter::isApplicable($field_definition)) {
      unset($form['options']['type']['#options']['commerce_price_calculated']);
    }
  }
}