On this page
Using Currency
Last updated on
30 September 2020
There are two main ways to utilize the code from this module.
Price storage does not belong as part of the Currency project. With entity references for config entities supported in Drupal core, any field or entity can use those to reference currencies, and add their own custom price/amount storage.
Basic usage
Configuration
Configure the Currency module under Administration > Configuration > Regional and Language:
- Currency: define or import custom currency types.
- Currency amount formatting: configure amount formatting for different locales.
- Currency exchange: configure how currency exchange rates should be retrieved.
Fields
Currency defines default field types:
- Entity Reference -> Other (Currency): A field of defined currencies.
- Exchange rate provider: @todo needs description
- Amount formatter: @todo needs description
Modules
This is the easiest method, as other modules utilize the Currency module.
API Calls
Currency provides three primary API calls.
Form
Adds a currency form item.
public function buildForm(array $form, FormStateInterface $form_state, $extra = NULL) {
$form["currency"] = [
'#type' => 'select',
'#title' => $this->t('Currency'),
'#options' => \Drupal::service('currency.form_helper')->getCurrencyOptions(),
'#required' => TRUE,
];
}
Storage
Uses entity storage to query currency formats.
/**
* Duble: \Drupal::service('currency.form_helper')->getCurrencyOptions().
*/
public static function formOptions() {
$currency_storage = \Drupal::entityManager()->getStorage('currency');
$currencies = $currency_storage->loadMultiple();
$options = [];
foreach ($currencies as $currency) {
// Do not show disabled currencies.
if ($currency->status()) {
$options[$currency->id()] = t('@currency_title (@currency_code)', [
'@currency_title' => $currency->label(),
'@currency_code' => $currency->id(),
]);
}
}
natcasesort($options);
return $options;
}
Custom-entity field
Adding a currency field as an Entity Reference.
$fields['currency'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Currency'))
->setSetting('target_type', 'currency')
->setSetting('handler', 'default')
->setDisplayOptions('view', [
'label' => 'hidden',
'type' => 'entity_reference_label',
'settings' => [
'link' => FALSE,
],
])
->setDisplayOptions('form', [
'type' => 'options_select',
]);Help improve this page
Page status: No known problems
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion