metatags_quick-4.0.x-dev/src/Form/MetatagsQuickAdminSettingsForm.php

src/Form/MetatagsQuickAdminSettingsForm.php
<?php

namespace Drupal\metatags_quick\Form;

use Drupal\Core\Entity\EntityFieldManager;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class MetatagsQuickAdminSettingsForm.
 *
 * @package Drupal\metatags_quick\Form
 */
class MetatagsQuickAdminSettingsForm extends ConfigFormBase {

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

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

  /**
   * Constructs a new MetatagsQuickAdminSettingsForm object.
   *
   * @param \Drupal\Core\Entity\EntityFieldManager $entity_field_manager
   *   The entity field manager.
   * @param \Drupal\Core\Entity\EntityTypeBundleInterface $entityTypeBundleInfo
   *   The entity type manager.
   */
  public function __construct(EntityFieldManager $entity_field_manager, EntityTypeBundleInfoInterface $entityTypeBundleInfo) {
    $this->entityFieldManager = $entity_field_manager;
    $this->entityTypeBundleInfo = $entityTypeBundleInfo;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'metatags_quick_admin_settings';
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('metatags_quick.settings');
    $known_tags = \Drupal::service('metatags_quick.known_tags')->getKnownTags();
    $module_path = \Drupal::service('extension.list.module')->getPath('metatags_quick');

    // Build the form elements.
    $form['global'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Global settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    ];

    foreach ($fields as $key => $field) {
      if ($field->module != 'metatags_quick') {
        continue;
      }
      $metatags_found = TRUE;
    }
    if (!$metatags_found) {
      $form['global']['basic_init'] = [
        '#markup' => t('No meta tags found in your installation') . '<br/>',
      ];
    }
    $form['global']['use_path_based'] = [
      '#type' => 'checkbox',
      '#title' => t('Use path-based meta tags'),
      '#default_value' => $this->config('metatags_quick_use_path_based', 1),
      '#return_value' => 1,
    ];
    $form['global']['remove_tab'] = [
      '#type' => 'checkbox',
      '#title' => t('Hide Path-based Metatags tab'),
      '#default_value' => $this->config('metatags_quick_remove_tab', 0),
    ];
    $form['global']['default_field_length'] = [
      '#type' => 'textfield',
      '#title' => t('Default maximum length'),
      '#description' => t('Default maximum length for the meta tag fields'),
      '#default_value' => $this->config('metatags_quick_default_field_length', 255),
    ];
    $form['global']['show_admin_hint'] = [
      '#type' => 'checkbox',
      '#title' => t('Show entities/bundles hint in admin'),
      '#default_value' => $this->config('metatags_quick_show_admin_hint', 1),
    ];
    $form['standard_tags'] = [
      '#type' => 'fieldset',
      '#title' => t('Create and attach'),
      '#description' => t('The following meta tags are known to the module and can be created automatically. However, you are not limited to this list and can define tags of your own using the Fields UI.'),
      '#collapsible' => TRUE,
      '#attached' => [
        'js' => [$module_path . '/js/admin.js'],
        'css' => [$module_path . '/css/admin.css'],
      ],
    ];
    if ($this->config('metatags_quick_show_admin_hint', 1)) {
      $form['standard_tags']['hint'] = [
        '#prefix' => '<div class="messages messages--status">',
        '#markup' => t('<strong>Hint</strong>: press on entity type name to edit individual bundles settings (you can hide this hint in global settings).'),
        '#suffix' => '</div>',
      ];
    }
    $header = [
      'title' => ['data' => new TranslatableMarkup('Bundle/entity')],
    ];
    foreach ($known_tags as $name => $tag) {
      $header[$name] = $tag['title'];
    }
    $bundles = $this->entityTypeBundleInfo->getBundleInfo();
    foreach ($bundles as $entity_type => $bundles) {
      $entity_type_info = $this->entityTypeBundleInfo->getDefinition($entity_type);
      if (!$entity_info->isFieldable()) {
        continue;
      }
      $form['bundles'][$entity_type] = [
        '#type' => 'details',
        '#title' => new TranslatableMarkup('@label settings', ['@label' => $entity_type_info->getLabel()]),
        '#open' => FALSE,
        '#attributes' => [
          'class' => [
            'entity-type-collapsible',
            'entity-type-collapsed',
            "entity-name-$entity_type",
          ],
        ],
      ];
      foreach ($known_tags as $name => $tag) {
        $bundle_workable[$name] = FALSE;
        $options[$entity_type]['data'][$name] = [
          'data' => [
            '#type' => 'checkbox',
            '#attributes' => ['class' => ['cb_bundle_parent', "cb_bundle_name_{$entity_type}_{$name}"]],
            '#return_value' => 1,
            '#checked' => FALSE,
          ],
        ];
      }
      // How do we mark that specific meta is already attached to bundle.
      $checked_markup = [
        '#markup' => theme(
          'image',
          [
            'uri' => 'core/misc/watchdog-ok.png',
            'width' => 18,
            'height' => 18,
            'alt' => 'ok',
            'title' => 'ok',
          ]
        ),
      ];

      foreach ($bundles as $key => $bundle) {
        // Which meta tags are set for this bundle?
        $meta_set = [];
        foreach ($field_instances as $entity_type => $list) {
          if (!array_key_exists($key, $list)) {
            continue;
          }
          foreach ($list[$key] as $bundle_instance) {
            $field_storage = \Drupal::entityTypeManager()->getStorage('field_storage_config')->load($bundle_instance->id);
            if ($field_storage && $field_storage->getEntityTypeId() === 'metatags_quick') {
              $meta_set[$bundle_instance->settings['meta_name']] = 1;
            }
          }
          $options[$entity_type . '_' . $key] = [
            'class' => ['entity_type_children', "entity_child_$entity_type"],
            'style' => 'display: none',
            'data' => [
              'title' => [
                'class' => ['entity_type_child_title'],
                'data' => $bundle['label'],
              ],
            ],
          ];
          foreach ($known_tags as $name => $tag) {
            $tag_name = $tag['meta_name'] ?? $name;
            if (empty($meta_set[$tag_name])) {
              // Mark parent bundle as workable - display checkbox.
              $bundle_workable[$name] = TRUE;
              $options[$entity_type . '_' . $key]['data'][$name] = [
                'data' => [
                  '#name' => $entity_type . '[' . $key . '][' . $name . ']',
                  '#type' => 'checkbox',
                  '#attributes' => ['class' => ['cb_bundle_child', "cb_child_{$entity_type}_{$name}"]],
                  '#return_value' => 1,
                  '#checked' => FALSE,
                ],
              ];
            }
            else {
              $options[$entity_type . '_' . $key]['data'][$name]['data'] = $checked_markup;
            }
          }
        }
      }
      // Now check if we have completely set bundles.
      foreach ($known_tags as $name => $tag) {
        if (!$bundle_workable[$name]) {
          $options[$entity_type]['data'][$name]['data'] = $checked_markup;
        }
      }
    }

    $form['standard_tags']['existing'] = [
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $options,
      '#empty' => t('No content available.'),
    ];

    $form['standard_tags']['basic_init_op'] = [
      '#type' => 'submit',
      '#value' => t('Attach'),
    ];
    $form['op'] = [
      '#value' => t('Submit'),
      '#type' => 'submit',
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config('metatags_quick.settings');

    $config
      ->set('use_path_based', $form_state->getValue('use_path_based'))
      ->set('remove_tab', $form_state->getValue('remove_tab'))
      ->set('default_field_length', $form_state->getValue('default_field_length'))
      ->set('show_admin_hint', $form_state->getValue('show_admin_hint'))
      ->save();

    if ($form_state->getTriggeringElement()['#value'] == $this->t('Attach')) {
      $this->fieldsCreateAttach($form_state->getValues());
    }
    else {
      $this->messenger()->addStatus($this->t('Meta tags (quick) settings saved'));
    }

    parent::submitForm($form, $form_state);
  }

  /**
   *
   */
  protected function fieldsCreateAttach($input) {
    foreach (\Drupal::entityTypeManager()->getDefinitions() as $entity_type_id => $entity_type) {
      if (!$entity_type->isFieldable()) {
        continue;
      }
    }
  }

}

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

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