class Price in Commerce Core 8.2
Same name in this branch
- 8.2 modules/price/src/Price.php \Drupal\commerce_price\Price
- 8.2 modules/price/src/Element/Price.php \Drupal\commerce_price\Element\Price
Provides a price form element.
Usage example:
$form['amount'] = [
'#type' => 'commerce_price',
'#title' => $this
->t('Amount'),
'#default_value' => [
'number' => '99.99',
'currency_code' => 'USD',
],
'#allow_negative' => FALSE,
'#size' => 60,
'#maxlength' => 128,
'#required' => TRUE,
'#available_currencies' => [
'USD',
'EUR',
],
];
Plugin annotation
@FormElement("commerce_price");
Hierarchy
- class \Drupal\Component\Plugin\PluginBase implements DerivativeInspectionInterface, PluginInspectionInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
- class \Drupal\Core\Render\Element\RenderElement implements ElementInterface
- class \Drupal\Core\Render\Element\FormElement implements FormElementInterface
- class \Drupal\commerce_price\Element\Price
- class \Drupal\Core\Render\Element\FormElement implements FormElementInterface
- class \Drupal\Core\Render\Element\RenderElement implements ElementInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
Expanded class hierarchy of Price
7 string references to 'Price'
- commerce_price.schema.yml in modules/
price/ config/ schema/ commerce_price.schema.yml - modules/price/config/schema/commerce_price.schema.yml
- ProductLayoutBuilderIntegrationTest::configureDefaultLayout in modules/
product/ tests/ src/ FunctionalJavascript/ ProductLayoutBuilderIntegrationTest.php - Configures a default layout for a product type.
- ProductVariationFieldInjectionTest::testInjectedVariationDefault in modules/
product/ tests/ src/ Functional/ ProductVariationFieldInjectionTest.php - Tests the fields from the attribute render.
- ProductVariationInlineForm::getTableFields in modules/
product/ src/ Form/ ProductVariationInlineForm.php - Gets the columns used to represent an entity in the IEF table.
- ProductVariationListBuilder::buildHeader in modules/
product/ src/ ProductVariationListBuilder.php - Builds the header row for the entity listing.
13 #type uses of Price
- AdjustmentDefaultWidget::formElement in modules/
order/ src/ Plugin/ Field/ FieldWidget/ AdjustmentDefaultWidget.php - Returns the form for a single field widget.
- AjaxPriceTestForm::buildForm in modules/
price/ tests/ modules/ commerce_price_test/ src/ Form/ AjaxPriceTestForm.php - Form constructor.
- BuyXGetY::buildConfigurationForm in modules/
promotion/ src/ Plugin/ Commerce/ PromotionOffer/ BuyXGetY.php - Form constructor.
- FixedAmountOffTrait::buildConfigurationForm in modules/
promotion/ src/ Plugin/ Commerce/ PromotionOffer/ FixedAmountOffTrait.php - ListPriceWidget::formElement in modules/
price/ src/ Plugin/ Field/ FieldWidget/ ListPriceWidget.php - Returns the form for a single field widget.
File
- modules/
price/ src/ Element/ Price.php, line 27
Namespace
Drupal\commerce_price\ElementView source
class Price extends FormElement {
/**
* {@inheritdoc}
*/
public function getInfo() {
$class = get_class($this);
return [
// List of currencies codes. If empty, all currencies will be available.
'#available_currencies' => [],
// The check is performed here so that it is cached.
'#price_inline_errors' => \Drupal::moduleHandler()
->moduleExists('inline_form_errors'),
'#size' => 10,
'#maxlength' => 128,
'#default_value' => NULL,
'#allow_negative' => FALSE,
'#attached' => [
'library' => [
'commerce_price/admin',
],
],
'#element_validate' => [
[
$class,
'moveInlineErrors',
],
],
'#process' => [
[
$class,
'processElement',
],
[
$class,
'processAjaxForm',
],
[
$class,
'processGroup',
],
],
'#pre_render' => [
[
$class,
'preRenderGroup',
],
],
'#input' => TRUE,
'#theme_wrappers' => [
'container',
],
];
}
/**
* Builds the commerce_price form element.
*
* @param array $element
* The initial commerce_price form element.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param array $complete_form
* The complete form structure.
*
* @return array
* The built commerce_price form element.
*
* @throws \InvalidArgumentException
* Thrown when #default_value is not an instance of
* \Drupal\commerce_price\Price.
*/
public static function processElement(array $element, FormStateInterface $form_state, array &$complete_form) {
$default_value = $element['#default_value'];
if (isset($default_value) && !self::validateDefaultValue($default_value)) {
throw new \InvalidArgumentException('The #default_value for a commerce_price element must be an array with "number" and "currency_code" keys.');
}
/** @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $currency_storage */
$currency_storage = \Drupal::service('entity_type.manager')
->getStorage('commerce_currency');
/** @var \Drupal\commerce_price\Entity\CurrencyInterface[] $currencies */
$currencies = $currency_storage
->loadMultiple();
$currency_codes = array_keys($currencies);
// Keep only available currencies.
$available_currencies = $element['#available_currencies'];
if (isset($available_currencies) && !empty($available_currencies)) {
$currency_codes = array_intersect($currency_codes, $available_currencies);
}
// Stop rendering if there are no currencies available.
if (empty($currency_codes)) {
return $element;
}
$fraction_digits = [];
foreach ($currencies as $currency) {
$fraction_digits[] = $currency
->getFractionDigits();
}
$element['#tree'] = TRUE;
$element['#attributes']['class'][] = 'form-type-commerce-price';
// Provide an example to the end user so that they know which decimal
// separator to use. This is the same pattern Drupal core uses.
$number_formatter = \Drupal::service('commerce_price.number_formatter');
$element['number'] = [
'#type' => 'commerce_number',
'#title' => $element['#title'],
'#title_display' => $element['#title_display'],
'#default_value' => $default_value ? $default_value['number'] : NULL,
'#required' => $element['#required'],
'#size' => $element['#size'],
'#maxlength' => $element['#maxlength'],
'#min_fraction_digits' => min($fraction_digits),
'#min' => $element['#allow_negative'] ? NULL : 0,
'#error_no_message' => TRUE,
'#description' => t('Format: @format', [
'@format' => $number_formatter
->format('9.99'),
]),
];
if (isset($element['#ajax'])) {
$element['number']['#ajax'] = $element['#ajax'];
}
if (count($currency_codes) == 1) {
$last_visible_element = 'number';
$currency_code = reset($currency_codes);
$element['number']['#field_suffix'] = $currency_code;
$element['currency_code'] = [
'#type' => 'hidden',
'#value' => $currency_code,
];
}
else {
$last_visible_element = 'currency_code';
$element['currency_code'] = [
'#type' => 'select',
'#title' => t('Currency'),
'#default_value' => $default_value ? $default_value['currency_code'] : NULL,
'#options' => array_combine($currency_codes, $currency_codes),
'#title_display' => 'invisible',
'#field_suffix' => '',
];
if (isset($element['#ajax'])) {
$element['currency_code']['#ajax'] = $element['#ajax'];
}
}
// Add the help text if specified.
if (!empty($element['#description'])) {
$element[$last_visible_element]['#description'] = $element['#description'];
}
// Remove the keys that were transferred to child elements.
unset($element['#size']);
unset($element['#maxlength']);
unset($element['#ajax']);
unset($element['#description']);
return $element;
}
/**
* Validates the default value.
*
* @param mixed $default_value
* The default value.
*
* @return bool
* TRUE if the default value is valid, FALSE otherwise.
*/
public static function validateDefaultValue($default_value) {
if (!is_array($default_value)) {
return FALSE;
}
if (!array_key_exists('number', $default_value) || !array_key_exists('currency_code', $default_value)) {
return FALSE;
}
return TRUE;
}
/**
* Moves inline errors from the "number" element to the main element.
*
* This ensures that they are displayed in the right place
* (below both number and currency_code, instead of between them).
*
* Only performed when the inline_form_errors module is installed.
*
* @param array $element
* The form element.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
public static function moveInlineErrors(array $element, FormStateInterface $form_state) {
$error = $form_state
->getError($element['number']);
if (!empty($error) && !empty($element['#price_inline_errors'])) {
$form_state
->setError($element, $error);
}
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
FormElement:: |
public static | function | Adds autocomplete functionality to elements. | |
FormElement:: |
public static | function | #process callback for #pattern form element property. | |
FormElement:: |
public static | function | #element_validate callback for #pattern form element property. | |
FormElement:: |
public static | function |
Determines how user input is mapped to an element's #value property. Overrides FormElementInterface:: |
15 |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
PluginBase:: |
protected | property | Configuration information passed into the plugin. | 1 |
PluginBase:: |
protected | property | The plugin implementation definition. | 1 |
PluginBase:: |
protected | property | The plugin_id. | |
PluginBase:: |
constant | A string which is used to separate base plugin IDs from the derivative ID. | ||
PluginBase:: |
public | function |
Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the definition of the plugin implementation. Overrides PluginInspectionInterface:: |
3 |
PluginBase:: |
public | function |
Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface:: |
|
PluginBase:: |
public | function | Determines if the plugin is configurable. | |
PluginBase:: |
public | function | Constructs a \Drupal\Component\Plugin\PluginBase object. | 92 |
Price:: |
public | function |
Returns the element properties for this element. Overrides ElementInterface:: |
|
Price:: |
public static | function | Moves inline errors from the "number" element to the main element. | |
Price:: |
public static | function | Builds the commerce_price form element. | |
Price:: |
public static | function | Validates the default value. | |
RenderElement:: |
public static | function | Adds Ajax information about an element to communicate with JavaScript. | |
RenderElement:: |
public static | function | Adds members of this group as actual elements for rendering. | |
RenderElement:: |
public static | function | Form element processing handler for the #ajax form property. | 1 |
RenderElement:: |
public static | function | Arranges elements into groups. | |
RenderElement:: |
public static | function |
Sets a form element's class attribute. Overrides ElementInterface:: |
|
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. |