You are here

public function Text3Widget::validate in Examples for Developers 3.x

Same name and namespace in other branches
  1. 8 field_example/src/Plugin/Field/FieldWidget/Text3Widget.php \Drupal\field_example\Plugin\Field\FieldWidget\Text3Widget::validate()

Validate the fields and convert them into a single value as text.

File

modules/field_example/src/Plugin/Field/FieldWidget/Text3Widget.php, line 70

Class

Text3Widget
Plugin implementation of the 'field_example_3text' widget.

Namespace

Drupal\field_example\Plugin\Field\FieldWidget

Code

public function validate($element, FormStateInterface $form_state) {

  // Validate each of the textfield entries.
  $values = [];
  foreach ([
    'r',
    'g',
    'b',
  ] as $colorfield) {
    $values[$colorfield] = $element[$colorfield]['#value'];

    // If they left any empty, we'll set the value empty and quit.
    if (strlen($values[$colorfield]) == 0) {
      $form_state
        ->setValueForElement($element, '');
      return;
    }

    // If they gave us anything that's not hex, reject it.
    if (strlen($values[$colorfield]) != 2 || !ctype_xdigit($values[$colorfield])) {
      $form_state
        ->setError($element[$colorfield], $form_state, $this
        ->t("Saturation value must be a 2-digit hexadecimal value between 00 and ff."));
    }
  }

  // Set the value of the entire form element.
  $value = strtolower(sprintf('#%02s%02s%02s', $values['r'], $values['g'], $values['b']));
  $form_state
    ->setValueForElement($element, $value);
}