public function CurrencyAmount::elementValidate in Currency 8.3
Implements form #element_validate callback.
File
- src/
Element/ CurrencyAmount.php, line 178
Class
- CurrencyAmount
- Provides an element to collect amounts of money and convert them to strings.
Namespace
Drupal\currency\ElementCode
public function elementValidate($element, FormStateInterface $form_state, array $form) {
$values = $form_state
->getValues();
$value = NestedArray::getValue($values, $element['#parents']);
$amount = $value['amount'];
$currency_code = $value['currency_code'];
// Confirm that the amount is numeric.
$amount = $this->input
->parseAmount($amount);
if ($amount === FALSE) {
$form_state
->setError($element['amount'], $this
->t('%title is not numeric.', [
'%title' => $element['#title'],
]));
}
// Confirm the amount lies within the allowed range.
/** @var \Drupal\currency\Entity\CurrencyInterface $currency */
$currency = $this->currencyStorage
->load($currency_code);
if ($element['#minimum_amount'] !== FALSE && bccomp($element['#minimum_amount'], $amount, 6) > 0) {
$form_state
->setError($element['amount'], $this
->t('The minimum amount is @amount.', [
'@amount' => $currency
->formatAmount($element['#minimum_amount']),
]));
}
elseif ($element['#maximum_amount'] !== FALSE && bccomp($amount, $element['#maximum_amount'], 6) > 0) {
$form_state
->setError($element['amount'], $this
->t('The maximum amount is @amount.', [
'@amount' => $currency
->formatAmount($element['#maximum_amount']),
]));
}
// The amount in $form_state is a human-readable, optionally localized
// string, which cannot be used by other code. $amount is a numeric string
// after running it through \Drupal::service('currency.input')->parseAmount().
$form_state
->setValueForElement($element, [
'amount' => $amount,
'currency_code' => $currency_code,
]);
}