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

src/Plugin/Field/FieldWidget/MultipleStringTextarea.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_textarea",
 *   label = @Translation("Text area (each value on a new line)"),
 *   field_types = {
 *     "string",
 *   },
 *   multiple_values = TRUE,
 * )
 */
class MultipleStringTextarea extends WidgetBase {

  protected string $separator = "\n";

  /**
   * {@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' => 'textarea',
      '#default_value' => implode($this->separator, $values),
    ];

    return $element;
  }

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

    foreach (explode($this->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