3 namespace Drupal\field_test\Plugin\Field\FieldWidget;
5 use Drupal\Core\Field\FieldDefinitionInterface;
6 use Drupal\Core\Field\FieldItemListInterface;
7 use Drupal\Core\Field\WidgetBase;
8 use Drupal\Core\Form\FormStateInterface;
9 use Symfony\Component\Validator\ConstraintViolationInterface;
12 * Plugin implementation of the 'test_field_widget_multiple' widget.
14 * The 'field_types' entry is left empty, and is populated through
15 * hook_field_widget_info_alter().
17 * @see field_test_field_widget_info_alter()
20 * id = "test_field_widget_multiple",
21 * label = @Translation("Test widget - multiple"),
22 * multiple_values = TRUE,
26 class TestFieldWidgetMultiple extends WidgetBase {
31 public static function defaultSettings() {
33 'test_widget_setting_multiple' => 'dummy test string',
34 ] + parent::defaultSettings();
40 public function settingsForm(array $form, FormStateInterface $form_state) {
41 $element['test_widget_setting_multiple'] = [
42 '#type' => 'textfield',
43 '#title' => t('Field test field widget setting'),
44 '#description' => t('A dummy form element to simulate field widget setting.'),
45 '#default_value' => $this->getSetting('test_widget_setting_multiple'),
54 public function settingsSummary() {
56 $summary[] = t('@setting: @value', ['@setting' => 'test_widget_setting_multiple', '@value' => $this->getSetting('test_widget_setting_multiple')]);
63 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
65 foreach ($items as $item) {
66 $values[] = $item->value;
69 '#type' => 'textfield',
70 '#default_value' => implode(', ', $values),
71 '#element_validate' => [[get_class($this), 'multipleValidate']],
79 public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, FormStateInterface $form_state) {
84 * Element validation helper.
86 public static function multipleValidate($element, FormStateInterface $form_state) {
87 $values = array_map('trim', explode(',', $element['#value']));
89 foreach ($values as $value) {
90 $items[] = ['value' => $value];
92 $form_state->setValueForElement($element, $items);
97 * Used in \Drupal\field\Tests\EntityReference\EntityReferenceAdminTest::testAvailableFormatters().
99 public static function isApplicable(FieldDefinitionInterface $field_definition) {
100 // Returns FALSE if machine name of the field equals field_onewidgetfield.
101 return $field_definition->getName() != "field_onewidgetfield";