Usage¶
Editing¶
Editors choose a currency from the select. On an optional field, - None - leaves the field empty or clears an existing value.
Validation¶
Every value must be an alphabetic code from currencies.yml, compared exactly: EUR is valid, eur and ZZZ are not. Withdrawn codes such as DEM stay valid, so historical records can still be saved; the widget simply does not offer them for new values.
An invalid value produces the violation "value is not an ISO 4217 currency code." It applies wherever entities are validated: forms, REST, JSON:API, and code that calls $entity->validate(). Values saved without validation, for example by a migration that skips it, are not checked.
Setting values in code¶
$node->set('field_invoice_currency', 'EUR');
$violations = $node->get('field_invoice_currency')->validate();
$node->save();
$code = $node->get('field_invoice_currency')->value;
Base fields¶
The field type can be used as a base field on a custom entity type:
$fields['currency'] = BaseFieldDefinition::create('currency_field')
->setLabel(t('Currency'))
->setSetting('display', 'AlphabeticCode')
->setDisplayOptions('form', ['type' => 'currency_widget'])
->setDisplayOptions('view', [
'type' => 'currency_formatter',
'settings' => ['display' => 'Currency'],
]);
Views¶
The field is exposed to Views like other single-column fields. Filters and sorts work on the stored code.
Sample values¶
Devel Generate and other callers of generateSampleValue() get a random current alphabetic code.