ttv_assistant-1.0.x-dev/src/Form/TTVAssistantSettingsForm.php

src/Form/TTVAssistantSettingsForm.php
<?php

namespace Drupal\ttv_assistant\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\ConfigFormBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Url;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\field\Entity\FieldConfig;

/**
 * Provides settings for TTV Assistant module.
 */
class TTVAssistantSettingsForm extends ConfigFormBase {

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

  /**
   * Constructs an TTVAssistantSettingsForm object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
   *   The module entity manager service.
   */
  public function __construct(
    ConfigFactoryInterface $config_factory,
    EntityTypeManagerInterface $entity_manager) {
    parent::__construct($config_factory);
    $this->entityTypeManager = $entity_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['ttv_assistant.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'ttv_assistant.settings';
  }

  /**
   * Build form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('ttv_assistant.settings');
    // General settings.
    $form['general'] = [
      '#type' => 'details',
      '#title' => t('General settings'),
      '#open' => TRUE,
    ];
    $form['general']['avatar'] = [
      '#type'          => 'managed_file',
      '#upload_location' => 'public://',
      '#upload_validators' => [
        'file_validate_extensions' => ['gif png jpg jpeg svg'],
      ],
      '#title'  => t('Assistant avatar'),
      '#default_value'  => $config->get('avatar') ?? NULL,
      '#theme' => 'image_widget',
      '#format' => 'image',
    ];

    $form['general']['found_message'] = [
      '#type' => 'textfield',
      '#default_value' => $config->get('found_message') ?? 'New tag found!',
      '#title' => t('Text message for found tags'),
      '#description' => t('Assistant message to notify new tags'),
    ];
    $form['general']['max_tag'] = [
      '#type' => 'number',
      '#default_value' => $config->get('max_tag') ?? 0,
      '#title' => t('Maximum recommend tags.'),
      '#description' => t('Maximum recommend tags, -1 to unlimit.'),
      '#min' => -1,
    ];
    $form['general']['case_sensitivity'] = [
      '#type' => 'checkbox',
      '#default_value' => $config->get('case_sensitivity') ?? 0,
      '#title' => t('Case sensitivity'),
      '#description' => t('Recommend tags by case sensitivity'),
    ];
    // Taxonomy list.
    $vocabularies = $this->entityTypeManager->getStorage('taxonomy_vocabulary')->loadMultiple();
    if ($vocabularies) {
      $vocabulary_option = [];
      foreach ($vocabularies as $key => $vocabulary) {
        $vocabulary_option[$key] = $vocabulary->get('name');
      }
      // Ignore to search.
      $form['general']['taxonomy_ignored'] = [
        '#type' => 'checkboxes',
        '#title' => t('Ignored vocabularies'),
        '#options' => $vocabulary_option,
        '#default_value' => $config->get("taxonomy_ignored") ?? [],
        '#description' => t('Check to ignore searching for recommend tags in these vocabularies'),
      ];
    }
    $form['general']['fixed_top'] = [
      '#type' => 'number',
      '#default_value' => $config->get('fixed_top') ?? 0,
      '#title' => t('Fixed top'),
      '#description' => t('Fixed height from top (px)'),
    ];

    // Content Type list.
    $entityFieldManager = \Drupal::service('entity_field.manager');
    $nodeTypeStorage    = $this->entityTypeManager->getStorage('node_type');
    $nodeTypes          = $nodeTypeStorage->loadMultiple();
    $form['node_type']  = [
      '#type' => 'details',
      '#title' => t('Content Types (Select fields to be search for tag when input complete)'),
      '#open' => FALSE,
    ];
    $search_field_types = [
      'text',
      'text_long',
      'text_with_summary',
      'string',
      'string_long',
      'list_string',
    ];
    foreach ($nodeTypes as $bundle => $node_type) {
      $form['node_type'][$bundle] = [
        '#type' => 'details',
        '#title' => $node_type->get('name'),
        '#open' => FALSE,
      ];
      $fields = $entityFieldManager->getFieldDefinitions('node', $bundle);
      $search_fields = [];

      if ($fields) {
        foreach ($fields as $field_name => $field) {
          // Get trigger fields for .js.
          if (in_array($field->getType(), $search_field_types)) {
            // Add handler for command.
            if ($field instanceof FieldConfig) {
              $search_fields[$field_name] = $field->getLabel();
            }
            elseif ($field instanceof BaseFieldDefinition) {
              $search_fields[$field_name] = $field->getLabel()->__toString();
            }
          }
        }
      }
      if ($search_fields) {
        $form['node_type'][$bundle]['fields__' . $bundle] = [
          '#type' => 'checkboxes',
          '#options' => $search_fields,
          '#default_value' => $config->get("fields__{$bundle}") ?? [],
          '#title' => t('Text fields to search for tags'),
        ];
      }
    }

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $values = $form_state->getUserInput();
    // Remove form system default values.
    unset($values['form_build_id'], $values['form_token'], $values['form_id'], $values['op']);
    $config = $this->config('ttv_assistant.settings');
    $cache_file = $config->getRawData()['values']['cache_file'] ?? 0;
    foreach ($values as $key => $value) {
      $config->set($key, $value);
    }
    $config->save();
  }

}

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

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