ColorFieldType.php 5.99 KB
Newer Older
targoo's avatar
WIP D8  
targoo committed
1 2 3 4 5 6 7 8
<?php

namespace Drupal\color_field\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
9
use Drupal\Core\StringTranslation\TranslatableMarkup;
targoo's avatar
WIP D8  
targoo committed
10 11 12 13 14 15
use Drupal\Core\TypedData\DataDefinition;

/**
 * Plugin implementation of the 'color_type' field type.
 *
 * @FieldType(
16
 *   id = "color_field_type",
targoo's avatar
WIP D8  
targoo committed
17 18
 *   label = @Translation("Color"),
 *   description = @Translation("Create and store color value."),
19 20
 *   default_widget = "color_field_widget_default",
 *   default_formatter = "color_field_formatter_text"
targoo's avatar
WIP D8  
targoo committed
21 22
 * )
 */
23 24
class ColorFieldType extends FieldItemBase {

25 26 27 28 29 30 31
  /**
   * {@inheritdoc}
   */
  public static function mainPropertyName() {
    return 'color';
  }

targoo's avatar
WIP D8  
targoo committed
32 33 34 35
  /**
   * {@inheritdoc}
   */
  public static function defaultFieldSettings() {
36
    return [
targoo's avatar
WIP D8  
targoo committed
37
      'opacity' => TRUE,
38
    ] + parent::defaultFieldSettings();
targoo's avatar
WIP D8  
targoo committed
39 40 41 42 43 44
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultStorageSettings() {
45
    return [
targoo's avatar
WIP D8  
targoo committed
46
      'format' => '#HEXHEX',
47
    ] + parent::defaultStorageSettings();
targoo's avatar
WIP D8  
targoo committed
48 49 50 51 52
  }

  /**
   * {@inheritdoc}
   */
targoo's avatar
test  
targoo committed
53 54 55
  public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
    $element = [];

56
    $element['format'] = [
targoo's avatar
test  
targoo committed
57
      '#type' => 'select',
58 59
      '#title' => $this->t('Format storage'),
      '#description' => $this->t('Choose how to store the color.'),
targoo's avatar
test  
targoo committed
60
      '#default_value' => $this->getSetting('format'),
61
      '#options' => [
62 63 64 65
        '#HEXHEX' => $this->t('#123ABC'),
        'HEXHEX' => $this->t('123ABC'),
        '#hexhex' => $this->t('#123abc'),
        'hexhex' => $this->t('123abc'),
66 67
      ],
    ];
targoo's avatar
WIP D8  
targoo committed
68

targoo's avatar
targoo committed
69 70
    $element += parent::storageSettingsForm($form, $form_state, $has_data);

targoo's avatar
test  
targoo committed
71 72
    return $element;
  }
targoo's avatar
WIP D8  
targoo committed
73

targoo's avatar
test  
targoo committed
74 75 76 77 78 79
  /**
   * {@inheritdoc}
   */
  public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
    $element = [];

80
    $element['opacity'] = [
targoo's avatar
test  
targoo committed
81
      '#type' => 'checkbox',
82 83
      '#title' => $this->t('Record opacity'),
      '#description' => $this->t('Whether or not to record.'),
targoo's avatar
test  
targoo committed
84
      '#default_value' => $this->getSetting('opacity'),
85
    ];
targoo's avatar
test  
targoo committed
86 87

    return $element;
targoo's avatar
WIP D8  
targoo committed
88 89 90 91 92 93
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
targoo's avatar
targoo committed
94
    $format = $field_definition->getSetting('format');
95
    $color_length = isset($format) ? strlen($format) : 7;
96 97 98
    return [
      'columns' => [
        'color' => [
targoo's avatar
test  
targoo committed
99
          'description' => 'The color value',
targoo's avatar
WIP D8  
targoo committed
100
          'type' => 'varchar',
targoo's avatar
test  
targoo committed
101
          'length' => $color_length,
targoo's avatar
WIP D8  
targoo committed
102
          'not null' => FALSE,
103 104
        ],
        'opacity' => [
targoo's avatar
WIP D8  
targoo committed
105 106 107 108
          'description' => 'The opacity/alphavalue property',
          'type' => 'float',
          'size' => 'tiny',
          'not null' => FALSE,
109 110 111 112 113 114
        ],
      ],
      'indexes' => [
        'color' => ['color'],
      ],
    ];
targoo's avatar
WIP D8  
targoo committed
115 116
  }

targoo's avatar
test  
targoo committed
117 118 119 120
  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
121
    // Prevent early t() calls by using the TranslatableMarkup.
targoo's avatar
test  
targoo committed
122
    $properties['color'] = DataDefinition::create('string')
123
      ->setLabel(new TranslatableMarkup('Color'));
targoo's avatar
test  
targoo committed
124 125

    $properties['opacity'] = DataDefinition::create('float')
126
      ->setLabel(new TranslatableMarkup('Opacity'));
targoo's avatar
test  
targoo committed
127 128 129 130

    return $properties;
  }

targoo's avatar
WIP D8  
targoo committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value = $this->get('color')->getValue();
    return $value === NULL || $value === '';
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
    $constraints = parent::getConstraints();

targoo's avatar
targoo committed
146 147
    $label = $this->getFieldDefinition()->getLabel();

148 149 150
    $constraints[] = $constraint_manager->create('ComplexData', [
      'color' => [
        'Regex' => [
151
          'pattern' => '/^#?(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$/i',
152 153 154
        ],
      ],
    ]);
targoo's avatar
test  
targoo committed
155

156
    if ($this->getSetting('opacity')) {
targoo's avatar
WIP D8  
targoo committed
157
      $min = 0;
158 159 160
      $constraints[] = $constraint_manager->create('ComplexData', [
        'opacity' => [
          'Range' => [
targoo's avatar
WIP D8  
targoo committed
161
            'min' => $min,
162 163 164 165
            'minMessage' => $this->t('%name: the opacity may be no less than %min.', ['%name' => $label, '%min' => $min]),
          ],
        ],
      ]);
targoo's avatar
WIP D8  
targoo committed
166 167

      $max = 1;
168 169 170
      $constraints[] = $constraint_manager->create('ComplexData', [
        'opacity' => [
          'Range' => [
targoo's avatar
WIP D8  
targoo committed
171
            'max' => $max,
172 173 174 175
            'maxMessage' => $this->t('%name: the opacity may be no greater than %max.', ['%name' => $label, '%max' => $max]),
          ],
        ],
      ]);
targoo's avatar
WIP D8  
targoo committed
176 177 178 179 180 181 182 183 184
    }

    return $constraints;
  }

  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
targoo's avatar
targoo committed
185 186 187 188 189
    $settings = $field_definition->getSettings();

    if ($format = $settings['format']) {
      switch ($format) {
        case '#HEXHEX':
190
          $values['color'] = '#111AAA';
targoo's avatar
targoo committed
191
          break;
192

targoo's avatar
targoo committed
193 194 195
        case 'HEXHEX':
          $values['color'] = '111111';
          break;
196

targoo's avatar
targoo committed
197
        case '#hexhex':
198
          $values['color'] = '#111aaa';
targoo's avatar
targoo committed
199
          break;
200

targoo's avatar
targoo committed
201 202 203 204 205 206 207 208 209
        case 'hexhex':
          $values['color'] = '111111';
          break;
      }
    }

    $values['opacity'] = 1;

    return $values;
targoo's avatar
WIP D8  
targoo committed
210 211
  }

212 213 214 215 216 217
  /**
   * {@inheritdoc}
   */
  public function preSave() {
    parent::preSave();

targoo's avatar
targoo committed
218 219
    if ($format = $this->getSetting('format')) {
      $color = $this->color;
220 221

      // Clean up data and format it.
targoo's avatar
targoo committed
222
      $color = trim($color);
223 224 225 226 227 228 229

      if (substr($color, 0, 1) === '#') {
        $color = substr($color, 1);
      }

      switch ($format) {
        case '#HEXHEX':
230
          $color = '#' . strtoupper($color);
231
          break;
232

233
        case 'HEXHEX':
234
          $color = strtoupper($color);
235
          break;
236

237
        case '#hexhex':
targoo's avatar
targoo committed
238
          $color = '#' . strtolower($color);
239
          break;
240

241
        case 'hexhex':
targoo's avatar
targoo committed
242
          $color = strtolower($color);
243 244 245
          break;
      }

targoo's avatar
targoo committed
246 247
      $this->color = $color;
    }
248 249 250 251

    if (!$this->getSetting('opacity')) {
      unset($this->opacity);
    }
252 253
  }

targoo's avatar
WIP D8  
targoo committed
254
}