datafield-1.x-dev/src/Plugin/DataField/FieldWidget/TextfieldWidget.php
src/Plugin/DataField/FieldWidget/TextfieldWidget.php
<?php
namespace Drupal\datafield\Plugin\DataField\FieldWidget;
use Drupal\Core\Field\Attribute\FieldWidget;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\datafield\Plugin\DataFieldWidgetInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;
/**
* Plugin implementation of the 'text_textfield' widget.
*/
#[FieldWidget(
id: 'text_format',
label: new TranslatableMarkup('Text format'),
field_types: ['text'],
)]
class TextfieldWidget implements DataFieldWidgetInterface {
use StringTranslationTrait;
/**
* {@inheritdoc}
*/
public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, FormStateInterface $form_state) {
$subfield = $element['#subfield'];
if (empty($element[$subfield]['format']['#access'])) {
// Ignore validation errors for formats that may not be changed,
// such as when existing formats become invalid.
// See \Drupal\filter\Element\TextFormat::processFormat().
return FALSE;
}
return $element;
}
/**
* {@inheritdoc}
*/
public function getFormElement(&$element, $item, $setting) {
if (!empty($setting['rows'])) {
$element['#rows'] = $setting['rows'];
}
if (!empty($element['placeholder'])) {
$element['#placeholder'] = $setting['placeholder'];
}
$element['#type'] = 'text_format';
$element['#format'] = 'basic_html';
$element['#base_type'] = 'textarea';
}
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
$options['size'] = 30;
$options['placeholder'] = t('Please type');
return $options;
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$widget_settings = $form['#settings'];
return [
'size' => [
'#type' => 'number',
'#title' => $this->t('Size'),
'#default_value' => $widget_settings['size'] ?? self::defaultSettings()['size'],
'#min' => 1,
],
'placeholder' => [
'#type' => 'textfield',
'#title' => $this->t('Placeholder'),
'#default_value' => $widget_settings['placeholder'] ?? self::defaultSettings()['placeholder'],
],
];
}
/**
* {@inheritdoc}
*/
public function massageFormValues($value, array $form, FormStateInterface $form_state) {
if (is_array($value) && isset($value['value'])) {
if ($value['value'] == '') {
return NULL;
}
return $value['value'];
}
return $value;
}
}
