xero-8.x-2.x-dev/src/Plugin/Field/FieldWidget/XeroTextfieldWidget.php

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

namespace Drupal\xero\Plugin\Field\FieldWidget;

use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Component\Utility\Random;
use Drupal\Core\Field\Attribute\FieldWidget;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\TypedDataManagerInterface;
use Drupal\xero\Plugin\Field\FieldType\XeroReference;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a simple textfield for entering GUID.
 *
 * @internal
 */
#[FieldWidget(
  id: 'xero_textfield',
  label: new TranslatableMarkup('Xero textfield'),
  field_types: ['xero_referenc'],
  multiple_values: TRUE,
)]
class XeroTextfieldWidget extends WidgetBase implements ContainerFactoryPluginInterface {

  /**
   * The typed data manager.
   *
   * @var \Drupal\Core\TypedData\TypedDataManagerInterface
   */
  protected $typedDataManager;

  /**
   * A random generator.
   *
   * @var \Drupal\Component\Utility\Random
   */
  protected $randomGenerator;

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return [
      'xero_type' => [],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['third_party_settings'],
      $container->get('typed_data_manager')
    );
  }

  /**
   * Initialization method.
   *
   * @param string $plugin_id
   *   The plugin id.
   * @param mixed $plugin_definition
   *   The plugin definition.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
   * @param array $settings
   *   The base field settings.
   * @param array $third_party_settings
   *   Third-party field settings.
   * @param \Drupal\Core\TypedData\TypedDataManagerInterface $typed_data_manager
   *   The typed_data.manager service.
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, TypedDataManagerInterface $typed_data_manager) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);

    $this->fieldDefinition = $field_definition;
    $this->settings = $settings;
    $this->thirdPartySettings = $third_party_settings;
    $this->typedDataManager = $typed_data_manager;
    $this->randomGenerator = new Random();
  }

  /**
   * Get the Xero data type definition.
   *
   * @param string $type
   *   The Xero type setting provided by this widget.
   *
   * @return array<string, mixed>|bool|null
   *   The Xero data type definition or FALSE.
   */
  protected function getXeroDefinition($type): array|null|bool {
    $types = XeroReference::getTypes();

    if (!in_array($type, $types)) {
      return FALSE;
    }

    try {
      $definition = $this->typedDataManager->getDefinition($type);
    }
    catch (PluginNotFoundException $e) {
      $definition = FALSE;
    }

    return $definition;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $settings = [];
    $type_options = [];

    $types = $this->getSetting('xero_type');
    foreach ($types as $type_name) {
      $definition = $this->getXeroDefinition($type_name);

      if ($definition) {
        $type_options[$type_name] = $definition['label'];
      }
    }

    if (empty($type_options)) {
      return $settings;
    }

    $settings[] = $this->t('Xero types: @types', [
      '@types' => implode(', ', $type_options),
    ]);
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $options = $this->getTypeOptions();

    $element['xero_type'] = [
      '#type' => 'select',
      '#title' => $this->t('Xero Type'),
      '#description' => $this->t('Select the Xero data type to use for this form.'),
      '#options' => $options,
      '#multiple' => TRUE,
      '#default_value' => $this->getSetting('xero_type'),
    ];

    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $options = $this->getTypeOptions($this->getSetting('xero_type'));

    $element += [
      '#type' => 'container',
      'type' => [
        '#type' => 'select',
        '#title' => $this->t('Xero type'),
        '#description' => $this->t('Select the Xero data type to associate.'),
        '#options' => $options,
        '#default_value' => $items[$delta] ? $items[$delta]->get('type') : NULL,
      ],
      'guid' => [
        '#type' => 'textfield',
        '#title' => $this->t('GUID'),
        '#description' => $this->t('Provide the globally-unique identifier for the Xero item.'),
        '#default_value' => $items[$delta] ? $items[$delta]->get('guid') : NULL,
        '#maxlength' => 38,
        '#placeholder' => $this->getGUIDPlaceholder(),
        '#attributes' => ['class' => ['text-full']],
        '#size' => 60,
      ],
      'label' => [
        '#type' => 'textfield',
        '#title' => $this->t('Description'),
        '#description' => $this->t('Describe the reference to the Xero item'),
        '#default_value' => $items[$delta] ? $items[$delta]->get('label') : NULL,
        '#maxlength' => 255,
        '#attributes' => ['class' => ['text-full']],
        '#size' => 60,
      ],
    ];

    return $element;
  }

  /**
   * Get the xero type options.
   *
   * @param array $available
   *   (Optional) Xero types to restrict to.
   *
   * @return array<string,string>
   *   An array of options for a select list.
   */
  protected function getTypeOptions(array $available = []) {
    $options = [];

    $types = XeroReference::getTypes();

    foreach ($types as $type_name) {
      if (in_array($type_name, $available)) {
        $definition = $this->getXeroDefinition($type_name);

        if ($definition) {
          $options[$type_name] = $definition['label'];
        }
      }
    }

    return $options;
  }

  /**
   * Provide a random GUID to act as a HTML placeholder attribute.
   *
   * @return string
   *   Random GUID for use as placeholder attribute.
   */
  protected function getGUIDPlaceholder() {
    $hash = strtolower(hash('ripemd128', md5($this->randomGenerator->string(100))));
    $guid = substr($hash, 0, 8) . '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4);
    $guid .= '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);

    return $guid;
  }

}

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

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