Numeric item min/max settings ignored if set to 0

Created on 20 December 2016, almost 8 years ago
Updated 24 November 2023, 12 months ago

Problem/Motivation

PHP's empty() function is not enough to check for $settings['min'] or $settings['max'] for numeric item - \Drupal\Core\Field\Plugin\Field\FieldType\NumericItemBase::getConstraints(), because their value can be numeric zero, and in such case constraint is not returned.

This results in possible invalid numeric values for items that have min or max boundary set to 0.

Rough example:

Custom entity class, baseFieldDefinitions()

    $fields['hour'] = BaseFieldDefinition::create('integer')
      ->setLabel(new TranslatableMarkup('Hour'))
      ->setSetting('min', 0)
      ->setSetting('max', 23);

Custom code

  $e = CustomEntity::create([ 'hour' => -100 ]);
  $violations = $e->validate();

Validation passes w/o errors, because NumericItemBase::getConstraints() does not return constraint to check for minimum.

Proposed resolution

Replace !empty() check with check for non-empty string (because an empty string is default value of min/max settings):

if ($settings['min'] !== '') {}

πŸ› Bug report
Status

Closed: duplicate

Version

11.0 πŸ”₯

Component
FieldΒ  β†’

Last updated about 4 hours ago

Created by

πŸ‡ΊπŸ‡¦Ukraine pingwin4eg Zaporizhia πŸ‡ΊπŸ‡¦

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024