Skip to content
Snippets Groups Projects

Fixing validation of min and max value in field config entity. Adding test unit for this

2 files
+ 41
1
Compare changes
  • Side-by-side
  • Inline
Files
2
@@ -33,6 +33,7 @@ public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
'#type' => 'number',
'#title' => $this->t('Minimum'),
'#default_value' => $settings['min'],
'#element_validate' => [[static::class, 'validateMinMax']],
'#description' => $this->t('The minimum value that should be allowed in this field. Leave blank for no minimum.'),
];
$element['max'] = [
@@ -59,6 +60,29 @@ public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
return $element;
}
/**
* Validate min and max value ensuring that min always is less than max value.
*
* @param array $element
* The element to be validated.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state instance.
* @param array $complete_form
* The form completed instance.
*/
public static function validateMinMax(array &$element, FormStateInterface &$form_state, array &$complete_form): void {
$settingsValue = $form_state->getValue('settings');
if (empty($settingsValue['min']) || empty($settingsValue['max'])) {
return;
}
// Ensure that the input is less than the #max property, if set.
if ((float) $settingsValue['min'] > (float) $settingsValue['max']) {
$form_state->setError($element, t('Min must be lower than or equal to %max.', ['%max' => $settingsValue['max']]));
}
}
/**
* {@inheritdoc}
*/
@@ -85,7 +109,12 @@ public function getConstraints() {
'value' => [
'Range' => [
'min' => $min,
'minMessage' => $this->t('%name: the value may be no less than %min.', ['%name' => $label, '%min' => $min]),
'minMessage' => $this->t('%name: the value may be no less than %min.',
[
'%name' => $label,
'%min' => $min,
]
),
],
],
]);
Loading