Same name and namespace in other branches
  1. 8.x-2.x src/Plugin/Field/FieldType/ColorFieldType.php \Drupal\color_field\Plugin\Field\FieldType\ColorFieldType::getConstraints() 1 comment

File

src/Plugin/Field/FieldType/ColorFieldType.php, line 84

Class

ColorFieldType
Plugin implementation of the 'color_type' field type.

Namespace

Drupal\color_field\Plugin\Field\FieldType

Code

public function getConstraints() : array {
    $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
    $constraints = parent::getConstraints();
    $label = $this->getFieldDefinition()
        ->getLabel();
    $constraints[] = $constraint_manager->create('ComplexData', [
        'color' => [
            'Regex' => [
                'pattern' => '/^#?(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$/i',
            ],
        ],
    ]);
    if ($this->getSetting('opacity')) {
        $min = 0;
        $constraints[] = $constraint_manager->create('ComplexData', [
            'opacity' => [
                'Range' => [
                    'min' => $min,
                    'minMessage' => $this->t('%name: the opacity may be no less than %min.', [
                        '%name' => $label,
                        '%min' => $min,
                    ]),
                ],
            ],
        ]);
        $max = 1;
        $constraints[] = $constraint_manager->create('ComplexData', [
            'opacity' => [
                'Range' => [
                    'max' => $max,
                    'maxMessage' => $this->t('%name: the opacity may be no greater than %max.', [
                        '%name' => $label,
                        '%max' => $max,
                    ]),
                ],
            ],
        ]);
    }
    return $constraints;
}