Skip to content
Snippets Groups Projects

Adding default value validation on NumberWidget

1 unresolved thread
Files
2
@@ -6,6 +6,7 @@
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\Number;
use Symfony\Component\Validator\ConstraintViolationInterface;
/**
@@ -75,6 +76,11 @@ public function formElement(FieldItemListInterface $items, $delta, array $elemen
'#placeholder' => $this->getSetting('placeholder'),
];
$buildInfo = $form_state->getBuildInfo();
if (!empty($buildInfo["form_id"]) && $buildInfo["form_id"] === 'field_config_form') {
$element['#element_validate'] = [[static::class, 'validateDefaultValue']];
    • I'm not sure we should be solving this with an additional element validate. This should be already handled by the constraints set by \Drupal\Core\Field\Plugin\Field\FieldType\NumericItemBase::getConstraints, so isn't there something wrong if the constraints aren't applied against the default value?

Please register or sign in to reply
}
// Set the step for floating point and decimal numbers.
switch ($this->fieldDefinition->getType()) {
case 'decimal':
@@ -114,4 +120,28 @@ public function errorElement(array $element, ConstraintViolationInterface $viola
return $element['value'];
}
/**
* Validates that default value is less than maximum and great the minimum.
*
* @param array[] $element
* The numeric element to be validated.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param array[] $complete_form
* The complete form structure.
*/
public static function validateDefaultValue(array &$element, FormStateInterface &$form_state, array &$complete_form): void {
if (!$form_state->getValue('set_default_value')) {
return;
}
$settingsValue = $form_state->getValue('settings');
if (is_numeric($settingsValue['min'])) {
$element['#min'] = (float) $settingsValue['min'];
}
if (is_numeric($settingsValue['max'])) {
$element['#max'] = (float) $settingsValue['max'];
}
Number::validateNumber($element, $form_state, $complete_form);
}
}
Loading