custom_field-1.0.x-dev/src/Plugin/CustomField/FieldWidget/EmailWidget.php
src/Plugin/CustomField/FieldWidget/EmailWidget.php
<?php
declare(strict_types=1);
namespace Drupal\custom_field\Plugin\CustomField\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\custom_field\Attribute\CustomFieldWidget;
use Drupal\custom_field\Plugin\CustomField\FieldType\EmailType;
use Drupal\custom_field\Plugin\CustomFieldTypeInterface;
use Drupal\custom_field\Plugin\CustomFieldWidgetBase;
/**
* Plugin implementation of the 'email' widget.
*/
#[CustomFieldWidget(
id: 'email',
label: new TranslatableMarkup('Email'),
category: new TranslatableMarkup('General'),
field_types: [
'email',
'string',
],
)]
class EmailWidget extends CustomFieldWidgetBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings(): array {
return [
'size' => 60,
'placeholder' => '',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function widget(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state, CustomFieldTypeInterface $field): array {
$element = parent::widget($items, $delta, $element, $form, $form_state, $field);
$settings = $this->getSettings() + static::defaultSettings();
// Add our widget type and additional properties and return.
return [
'#type' => 'email',
'#maxlength' => EmailType::EMAIL_MAX_LENGTH,
'#placeholder' => $settings['placeholder'] ?? NULL,
'#size' => $settings['size'] ?? NULL,
] + $element;
}
/**
* {@inheritdoc}
*/
public function widgetSettingsForm(FormStateInterface $form_state, CustomFieldTypeInterface $field): array {
$element = parent::widgetSettingsForm($form_state, $field);
$settings = $this->getSettings() + static::defaultSettings();
$element['size'] = [
'#type' => 'number',
'#title' => $this->t('Size of textfield'),
'#default_value' => $settings['size'],
'#required' => TRUE,
'#min' => 1,
];
$element['placeholder'] = [
'#type' => 'textfield',
'#title' => $this->t('Placeholder'),
'#default_value' => $settings['placeholder'],
'#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
];
return $element;
}
}
