public static function ScssNumber::validateNumber in SCSS Compiler 1.0.x
Validate a number element's value on form submission.
If a value is required, but none was submitted, an error will be added.
If a value is provided, a unit is required, but none was selected, an error will be added.
Parameters
array $element: The element that should be validated.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
array $complete_form: The complete form.
File
- src/
Element/ ScssNumber.php, line 518
Class
- ScssNumber
- A form element to represent Sass numbers with a unit.
Namespace
Drupal\compiler_scss\ElementCode
public static function validateNumber(array &$element, FormStateInterface $form_state, array &$complete_form) {
// Extract the input value from the element.
$input = self::getValue($element);
// Extract the value & unit from this element's input (if available).
$value = $input['value'] ?? NULL;
$unit = $input['unit'] ?? NULL;
// Check if no value was submitted where one was required.
if (!is_numeric($value) && self::isRequired($element)) {
$error = $element['#title'] ? t('%name requires a value.', [
'%name' => $element['#title'],
]) : t('This field requires a value.');
$form_state
->setError($element['value'], $error);
}
// Determine whether a unit is required for this element.
$unit_required = is_numeric($value) && self::isUnitRequired($element);
// Check if no (valid) unit was selected where one was required.
if (!array_key_exists($unit, self::getAllowedUnits()) && $unit_required) {
$error = $element['#title'] ? t('%name requires a unit.', [
'%name' => $element['#title'],
]) : t('This field requires a unit.');
$form_state
->setError($element['unit'], $error);
}
// Check if only a unit was submitted.
if (!is_numeric($value) && !empty($unit)) {
$error = $element['#title'] ? t('%name cannot have only a unit.', [
'%name' => $element['#title'],
]) : t('This field cannot have only a unit.');
// Only complain about empty values with a unit if the unit isn't forced.
if ($element['unit']['#type'] !== 'hidden') {
$form_state
->setError($element['unit'], $error);
}
else {
$form_state
->setValueForElement($element['unit'], NULL);
}
}
// Canonicalize the element value and store it in the form state.
$unit = is_numeric($value) ? array_filter([
'unit' => $unit,
]) : [];
$value = is_numeric($value) ? [
'value' => $value,
] : [];
$form_state
->setValueForElement($element, $value + $unit ?: NULL);
}