entitytype_filter-1.0.x-dev/src/Form/FilterFieldTypesForm.php

src/Form/FilterFieldTypesForm.php
<?php

namespace Drupal\entitytype_filter\Form;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldTypePluginManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\entitytype_filter\EntitySearchService;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Defines a form for field type selection.
 */
class FilterFieldTypesForm extends FormBase {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $account;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The field type plugin manager.
   *
   * @var \Drupal\Core\Field\FieldTypePluginManagerInterface
   */
  protected $fieldTypePluginManager;

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * The cache backend instance.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cache;

  /**
   * The entity search service.
   *
   * @var \Drupal\entitytype_filter\EntitySearchService
   */
  protected $entitySearchService;

  /**
   * Constructs a FilterFieldTypesForm object.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_plugin_manager
   *   The field type plugin manager.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   * @param \Drupal\Core\Cache\CacheBackendInterface $static_cache
   *   The cache backend instance.
   * @param \Drupal\entitytype_filter\EntitySearchService $entity_search_service
   *   The entity search service.
   */
  public function __construct(AccountInterface $account, EntityTypeManagerInterface $entity_type_manager, FieldTypePluginManagerInterface $field_type_plugin_manager, EntityFieldManagerInterface $entity_field_manager, MessengerInterface $messenger, CacheBackendInterface $static_cache, EntitySearchService $entity_search_service) {
    $this->account = $account;
    $this->entityTypeManager = $entity_type_manager;
    $this->fieldTypePluginManager = $field_type_plugin_manager;
    $this->entityFieldManager = $entity_field_manager;
    $this->messenger = $messenger;
    $this->cache = $static_cache;
    $this->entitySearchService = $entity_search_service;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    // Instantiates this form class.
    return new static(
      // Load the service required to construct this class.
      $container->get('current_user'),
      $container->get('entity_type.manager'),
      $container->get('plugin.manager.field.field_type'),
      $container->get('entity_field.manager'),
      $container->get('messenger'),
      $container->get('cache.default'),
      $container->get('entitytype_filter.search_service')
    );
  }

  /**
   * Form ID of FilterFieldTypesForm.
   */
  public function getFormId() {
    return 'entitytype_filter_form';
  }

  /**
   * Builds FilterFieldTypesForm.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $output = [];
    $type_options = [];

    $config_types = $this->entitySearchService->getBundleConfigEntityTypes(TRUE);
    $options = array_map(fn($item) => $this->t("@label", ['@label' => $item['label']]), $config_types);
    $options = ['none' => $this->t('- Select a Value -')] + $options;

    $type_options['all'] = 'All';
    foreach ($this->fieldTypePluginManager->getGroupedDefinitions($this->fieldTypePluginManager->getUiDefinitions()) as $field_types) {
      foreach ($field_types as $name => $field_type) {
        $type_options[$name] = !is_string($field_type['label']) ? ($field_type['label'])->__toString() : $field_type['label'];
      }
    }

    $output = $this->buildFilteredFieldsList($form_state, $config_types);

    $form['#tree'] = TRUE;
    $header = [
      'bundle_name' => $this->t('<b>Bundle Machine Name</b>'),
      'field_label' => $this->t('<b>Field Label</b>'),
      'field_name' => $this->t('<b>Field Machine Name</b>'),
      'field_type' => $this->t('<b>Field Type</b>'),
    ];

    $form['filter_entity_types_table'] = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $output,
      '#weight' => 35,
      '#empty' => $this->t('No Fields Exists.'),
    ];

    $form['conditional-wrapper'] = [
      '#prefix' => '<div class="conditional-wrapper">',
      '#suffix' => '</div>',
    ];
    $form['conditional-wrapper']['fselect_entity_type'] = [
      '#type' => 'select',
      '#title' => $this->t('Select Entity Type'),
      '#options' => $options,
      '#default_value' => $options['none'],
    ];

    $form['conditional-wrapper']['fselect_field_type'] = [
      '#type' => 'select',
      '#title' => $this->t('Select Field Type'),
      '#options' => $type_options,
      '#default_value' => $type_options['all'],
    ];

    $form['download_table_csv'] = [
      '#type' => 'button',
      '#value' => '',
      '#weight' => 40,
      '#attributes' => [
        'id' => 'download_fields_table_as_csv',
        'title' => 'Download as CSV',
      ],
    ];

    $form['conditional-wrapper']['actions'] = [
      '#type' => 'actions',
      '#weight' => 30,
    ];
    $form['conditional-wrapper']['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Search'),
      '#attributes' => [
        'class' => ['button--primary'],
      ],
    ];

    $form['#attached']['library'][] = 'entitytype_filter/filter_fields_by_type';
    return $form;
  }

  /**
   * Implements validateForm().
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
  }

  /**
   * Implements submitForm().
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild(TRUE);
  }

  /**
   * Implements getEntityFieldsData().
   */
  public function getEntityFieldsData($entity_type_id, $bundle_id) {
    $fields = [];
    $field_defs = $this->entityFieldManager->getFieldDefinitions($entity_type_id, $bundle_id);
    $base_field_defs = $this->entityFieldManager->getBaseFieldDefinitions($entity_type_id, $bundle_id);

    foreach ($field_defs as $key => $value) {
      if (!array_key_exists($key, $base_field_defs)) {
        $fields[$entity_type_id . '.' . $bundle_id . '.' . $key] = $value;
      }
    }
    return $fields;
  }

  /**
   * Builds a list of filtered fields based on selected entity and field type.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   * @param array $config_types
   *   The config entity types data used for getting bundle_of values.
   *
   * @return array
   *   The filtered field info array keyed by field name.
   */
  protected function buildFilteredFieldsList(FormStateInterface $form_state, array $config_types): array {
    $output = [];

    $values = $form_state->getValues()['conditional-wrapper'] ?? [];
    $selected_entity_type = $values['fselect_entity_type'] ?? NULL;
    $selected_field_type = $values['fselect_field_type'] ?? NULL;

    if ($selected_entity_type === 'none') {
      $this->messenger->addWarning("Please select the Entity Type.");
      return [];
    }

    if (!$selected_entity_type || !$selected_field_type) {
      return [];
    }

    $cache_id = 'entity_storage_' . $selected_entity_type;
    $fields_data = [];

    if ($cache = $this->cache->get($cache_id)) {
      $entity_types = $cache->data;
    }
    else {
      $entity_types = $this->entityTypeManager->getStorage($selected_entity_type)->loadMultiple();
      $this->cache->set($cache_id, $entity_types, 86400);
    }

    foreach ($entity_types as $type) {
      $type_id = $type->id();
      $fields = $this->getEntityFieldsData($config_types[$selected_entity_type]['bundle_of'], $type_id);
      $fields_data += $fields;
    }

    $field_type_options = $this->entitySearchService->getGroupedFieldTypeOptions();
    $selected_field_type = explode(':', $selected_field_type)[2] ?? $selected_field_type;

    foreach ($fields_data as $field) {
      $handler = $field->getSetting('handler');
      $primary_type = $handler ? explode(':', $handler)[1] : NULL;
      $primary_type_label = $primary_type ? ucfirst(str_replace('_', ' ', $primary_type)) : "";

      $field_type = $this->entitySearchService->recursiveSearchKeyMap($field->getType(), $field_type_options) ?: $field->getType();
      $field_type_machine_name = $handler ? explode(':', $handler)[1] : $field->getType();

      if ($selected_field_type == 'all' || $selected_field_type == $field_type_machine_name) {
        $output[$field->id()] = [
          'bundle_name' => $field->getTargetBundle(),
          'field_label' => $field->label(),
          'field_name' => $field->getName(),
          'field_type' => !empty($primary_type_label) ? $primary_type_label : $field_type,
        ];
      }
    }

    return $output;
  }

}

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

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