View source
<?php
namespace Drupal\field_test\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;
class TestFieldWidgetMultiple extends WidgetBase {
public static function defaultSettings() {
return [
'test_widget_setting_multiple' => 'dummy test string',
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_widget_setting_multiple'] = [
'#type' => 'textfield',
'#title' => t('Field test field widget setting'),
'#description' => t('A dummy form element to simulate field widget setting.'),
'#default_value' => $this
->getSetting('test_widget_setting_multiple'),
'#required' => FALSE,
];
return $element;
}
public function settingsSummary() {
$summary = [];
$summary[] = t('@setting: @value', [
'@setting' => 'test_widget_setting_multiple',
'@value' => $this
->getSetting('test_widget_setting_multiple'),
]);
return $summary;
}
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$values = [];
foreach ($items as $item) {
$values[] = $item->value;
}
$element += [
'#type' => 'textfield',
'#default_value' => implode(', ', $values),
'#element_validate' => [
[
static::class,
'multipleValidate',
],
],
];
return $element;
}
public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, FormStateInterface $form_state) {
return $element;
}
public static function multipleValidate($element, FormStateInterface $form_state) {
$values = array_map('trim', explode(',', $element['#value']));
$items = [];
foreach ($values as $value) {
$items[] = [
'value' => $value,
];
}
$form_state
->setValueForElement($element, $items);
}
public static function isApplicable(FieldDefinitionInterface $field_definition) {
return $field_definition
->getName() != "field_onewidgetfield";
}
}