public function DoubleField::getConstraints in Double Field 8.3
Same name and namespace in other branches
- 4.x src/Plugin/Field/FieldType/DoubleField.php \Drupal\double_field\Plugin\Field\FieldType\DoubleField::getConstraints()
@TODO: Find a way to disable constraints for default field values.
Overrides TypedData::getConstraints
File
- src/
Plugin/ Field/ FieldType/ DoubleField.php, line 292
Class
- DoubleField
- Plugin implementation of the 'double_field' field type.
Namespace
Drupal\double_field\Plugin\Field\FieldTypeCode
public function getConstraints() {
$constraint_manager = \Drupal::typedDataManager()
->getValidationConstraintManager();
$constraints = parent::getConstraints();
$settings = $this
->getSettings();
$subconstrains = [];
foreach ([
'first',
'second',
] as $subfield) {
$subfield_type = $settings['storage'][$subfield]['type'];
$is_list = $settings[$subfield]['list'] && static::isListAllowed($subfield_type);
if ($is_list && $settings[$subfield]['allowed_values']) {
$allowed_values = array_keys($settings[$subfield]['allowed_values']);
$subconstrains[$subfield]['AllowedValues'] = $allowed_values;
}
if ($subfield_type == 'string' || $subfield_type == 'telephone') {
$subconstrains[$subfield]['Length']['max'] = $settings['storage'][$subfield]['maxlength'];
}
// Allowed values take precedence over the range constraints.
$numeric_types = [
'integer',
'float',
'numeric',
];
if (!$settings[$subfield]['list'] && in_array($subfield_type, $numeric_types)) {
if (is_numeric($settings[$subfield]['min'])) {
$subconstrains[$subfield]['Range']['min'] = $settings[$subfield]['min'];
}
if (is_numeric($settings[$subfield]['max'])) {
$subconstrains[$subfield]['Range']['max'] = $settings[$subfield]['max'];
}
}
if ($subfield_type == 'email') {
$subconstrains[$subfield]['Length']['max'] = Email::EMAIL_MAX_LENGTH;
}
if ($settings[$subfield]['required']) {
// NotBlank validator is not suitable for booleans because it does not
// recognize '0' as an empty value.
if ($subfield_type == 'boolean') {
$subconstrains[$subfield]['NotEqualTo']['value'] = 0;
$subconstrains[$subfield]['NotEqualTo']['message'] = $this
->t('This value should not be blank.');
}
else {
$subconstrains[$subfield]['NotBlank'] = [];
}
}
}
$constraints[] = $constraint_manager
->create('ComplexData', $subconstrains);
return $constraints;
}