improvements-2.x-dev/src/Plugin/Field/FieldWidget/MultipleStringTextfield.php

src/Plugin/Field/FieldWidget/MultipleStringTextfield.php
<?php

namespace Drupal\improvements\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * @FieldWidget(
 *   id = "multiple_string_textfield",
 *   label = @Translation("Textfield (values by a comma)"),
 *   field_types = {
 *     "string",
 *   },
 *   multiple_values = TRUE,
 * )
 */
class MultipleStringTextfield extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings(): array {
    return [
      'separator' => ', ',
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state): array {
    $element = parent::settingsForm($form, $form_state);

    $element['separator'] = [
      '#type' => 'textfield',
      '#title' => t('Separator'),
      '#default_value' => $this->getSetting('separator'),
    ];

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary(): array {
    return [
      $this->t('Separator') . ': ' . $this->getSetting('separator'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state): array {
    $values = array_map(function (FieldItemInterface $item) {
      return $item->value;
    }, iterator_to_array($items));

    $element['value'] = $element + [
      '#type' => 'textfield',
      '#default_value' => implode($this->getSetting('separator'), $values),
    ];

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state): array {
    $new_values = [];

    foreach (explode($this->getSetting('separator'), $values['value']) as $value) {
      $value = trim($value);
      if ($value !== '') {
        $new_values[] = ['value' => $value];
      }
    }

    return $new_values;
  }

  /**
   * {@inheritDoc}
   */
  public static function isApplicable(FieldDefinitionInterface $field_definition): bool {
    $cardinality = $field_definition->getFieldStorageDefinition()->getCardinality();
    return $cardinality > 1 || $cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc