TextWidget.php

Same filename in this branch
  1. 3.x modules/field_permission_example/src/Plugin/Field/FieldWidget/TextWidget.php
Same filename and directory in other branches
  1. 4.0.x modules/field_permission_example/src/Plugin/Field/FieldWidget/TextWidget.php
  2. 4.0.x modules/field_example/src/Plugin/Field/FieldWidget/TextWidget.php

Namespace

Drupal\field_example\Plugin\Field\FieldWidget

File

modules/field_example/src/Plugin/Field/FieldWidget/TextWidget.php

View source
<?php

namespace Drupal\field_example\Plugin\Field\FieldWidget;

use Drupal\Component\Utility\Color;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'field_example_text' widget.
 *
 * @FieldWidget(
 *   id = "field_example_text",
 *   module = "field_example",
 *   label = @Translation("RGB value as #ffffff"),
 *   field_types = {
 *     "field_example_rgb"
 *   }
 * )
 */
class TextWidget extends WidgetBase {
    
    /**
     * {@inheritdoc}
     */
    public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
        $value = $items[$delta]->value ?? '';
        $element += [
            '#type' => 'textfield',
            '#default_value' => $value,
            '#size' => 7,
            '#maxlength' => 7,
            '#element_validate' => [
                [
                    $this,
                    'validate',
                ],
            ],
        ];
        return [
            'value' => $element,
        ];
    }
    
    /**
     * Validate the color text field.
     */
    public function validate($element, FormStateInterface $form_state) {
        $value = $element['#value'];
        if (strlen($value) === 0) {
            $form_state->setValueForElement($element, '');
            return;
        }
        if (!Color::validateHex($value)) {
            $form_state->setError($element, $this->t('Color must be a 3- or 6-digit hexadecimal value, suitable for CSS.'));
        }
    }

}

Classes

Title Deprecated Summary
TextWidget Plugin implementation of the 'field_example_text' widget.