function Text3Widget::formElement
Same name in other branches
- 4.0.x modules/field_example/src/Plugin/Field/FieldWidget/Text3Widget.php \Drupal\field_example\Plugin\Field\FieldWidget\Text3Widget::formElement()
Overrides WidgetInterface::formElement
File
-
modules/
field_example/ src/ Plugin/ Field/ FieldWidget/ Text3Widget.php, line 26
Class
- Text3Widget
- Plugin implementation of the 'field_example_3text' widget.
Namespace
Drupal\field_example\Plugin\Field\FieldWidgetCode
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$value = $items[$delta]->value ?? '';
// Parse the single hex string into RBG values.
if (!empty($value)) {
preg_match_all('@..@', substr($value, 1), $match);
}
else {
$match = [
[],
];
}
// Set up the form element for this widget.
$element += [
'#type' => 'details',
'#element_validate' => [
[
$this,
'validate',
],
],
];
// Add in the RGB textfield elements.
foreach ([
'r' => $this->t('Red'),
'g' => $this->t('Green'),
'b' => $this->t('Blue'),
] as $key => $title) {
$element[$key] = [
'#type' => 'textfield',
'#title' => $title,
'#size' => 2,
'#default_value' => array_shift($match[0]),
'#attributes' => [
'class' => [
'rgb-entry',
],
],
'#description' => $this->t('The 2-digit hexadecimal representation of @color saturation, like "a1" or "ff"', [
'@color' => $title,
]),
];
// Since Form API doesn't allow a fieldset to be required, we
// have to require each field element individually.
if ($element['#required']) {
$element[$key]['#required'] = TRUE;
}
}
return [
'value' => $element,
];
}