metatags_quick-4.0.x-dev/metatags_quick.admin.inc

metatags_quick.admin.inc
<?php

/**
 * @file
 */

use Drupal\Component\Render\FormattableMarkup;
use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Link;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\Markup;
use Drupal\Core\Site\Settings;
use Drupal\Core\Url;
use Drupal\field\Entity\FieldStorageConfig;

/**
 * General settings form.
 *
 * @return renderable array
 */
function metatags_quick_admin_settings() {
  $current_settings = Settings::get('metatags_quick_settings', _metatags_quick_settings_default());
  $module_path = \Drupal::service('extension.list.module')->getPath('metatags_quick');
  $field_name = '';
  $fields = FieldStorageConfig::loadByName('node', $field_name);
  $metatags_found = FALSE;

  include_once $module_path . '/known_tags.inc';
  $known_tags = _metatags_quick_known_fields();

  $form['global'] = [
    '#type' => 'fieldset',
    '#title' => 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' => Settings::get('metatags_quick_use_path_based', 1),
    '#return_value' => 1,
  ];
  $form['global']['remove_tab'] = [
    '#type' => 'checkbox',
    '#title' => t('Hide Path-based Metatags tab'),
    '#default_value' => Settings::get('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' => Settings::get('metatags_quick_default_field_length', 255),
  ];
  $form['global']['show_admin_hint'] = [
    '#type' => 'checkbox',
    '#title' => t('Show entities/bundles hint in admin'),
    '#default_value' => Settings::get('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 (Settings::get('metatags_quick_show_admin_hint', 1)) {
    $form['standard_tags']['hint'] = [
      '#prefix' => '<div class="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>',
    ];
  }

  $field_instances = \Drupal::entityTypeManager()->getStorage('field_config')->loadMultiple();

  // Build the sortable table header.
  $header = [
    'title' => ['data' => t('Bundle/entity')],
  ];
  foreach ($known_tags as $name => $tag) {
    $header[$name] = $tag['title'];
  }
  // $header['_select_all'] = t('Select all');
  $nodeBundles = \Drupal::service('entity_type.manager')->getStorage('node_type')->loadMultiple();
  foreach ($nodeBundles as $entity_type => $bundles) {
    $entityType = $entityTypeManager->getDefinition($entity_type);

    if (!$entityType->isFieldable()) {
      continue;
    }

    $options[$entity_type]['data'] = [
      'title' => [
        'class' => ['entity_type_collapsible', 'entity_type_collapsed', "entity_name_$entity_type"],
        'data' => Markup::create((string) new FormattableMarkup($entityTypeLabel, [])),
      ],
    ];
    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,
        ],
      ];
    }
    /*$options[$entity_type]['data']['_select_all'] = array(
    'data' => array(
    '#type' => 'checkbox',
    '#return_value' => 1,
    '#checked' => FALSE,
    ),
    );*/

    // How do we mark that specific meta is already attached to bundle.
    $checked_markup = [
      '#markup' => theme('image',
        [
          'path' => '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[$entity_type][$key] as $bundle_instance) {
        if ($bundle_instance['widget']['module'] == 'metatags_quick') {
          $field_info = FieldStorageConfig::load($bundle_instance['field_id']);
          $meta_set[$field_info['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;
        }
      }
      /*$options[$entity_type . '_' . $key]['data']['_select_all']['data'] = array(
      '#type' => 'checkbox',
      '#return_value' => 1,
      '#checked' => FALSE,
      );*/
    }
    // 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 $form;
}

/**
 * Path-based meta tags editing form.
 *
 * @param string $path
 *   - path being edited.
 */
function metatags_quick_admin_path($form, &$form_state) {
  $args = func_get_args();
  if (count($args) > 3) {
    $lang = $args[2];
    $path = $args[3];
  }
  else {
    return MENU_ACCESS_DENIED;
  }

  $controller = \Drupal::service('entity_type.manager')->getStorage('metatags_path_based');
  ;
  // @todo Drupal Rector Notice: Please delete the following comment after you've made any necessary changes.
  // You will need to use `\Drupal\core\Database\Database::getConnection()` if you do not yet have access to the container here.
  $entity_id = \Drupal::database()->select('metatags_quick_path_based', 'm')
    ->fields('m', ['id'])
    ->condition('lang', $lang)
    ->condition('path', $path)
    ->execute()
    ->fetchField();
  if (!$entity_id) {
    // @todo Drupal Rector Notice: Please delete the following comment after you've made any necessary changes.
    // You will need to use `\Drupal\core\Database\Database::getConnection()` if you do not yet have access to the container here.
    $entity_id = \Drupal::database()->insert('metatags_quick_path_based')
      ->fields(['lang' => $lang, 'path' => $path])
      ->execute();
  }
  $entity_type_manager = \Drupal::service('entity_type.manager');
  $entity_type = 'metatags_path_based';
  $view_mode = 'default';
  $form_display = $entity_type_manager->getStorage('entity_form_display')->load($entity_type . '.' . $view_mode);

  $entities = $controller->load([$entity_id]);
  $form_state['entity'] = $entities[$entity_id];

  $form_display->buildForm($entities[$entity_id], $form, $form_state);
  // Do we have any fields attached?
  $childen = Element::children($form);
  if (!$childen) {
    $form['empty_message'] = [
      '#markup' => t('No fields attached to the path-based meta tags. Please !define them first in the module settings screen',
      ),
    ];
  }
  $form['op'] = [
    '#value' => t('Submit'),
    '#type' => 'submit',
  ];
  return $form;
}

/**
 *
 */
function metatags_quick_admin_path_validate($form, &$form_state) {
  $entityFormValidator = \Drupal::service(EntityFormValidatorInterface::class);
  $entityFormValidator->validateFormFields('metatags_path_based', $form, $form_state);
}

/**
 *
 */
function metatags_quick_admin_path_submit($form, &$form_state) {
  $entity = $form_state->getFormObject()->getEntity();
  if (!$entity) {
    /** @var \Drupal\Core\Messenger\MessengerInterface $messenger */
    $messenger = \Drupal::service(MessengerInterface::class);
    $messenger->addError(t('Wrong path'));
    return;
  }

  /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager */
  $entityTypeManager = \Drupal::service(EntityTypeManagerInterface::class);
  $entityType = $entity->getEntityTypeId();
  $storage = $entityTypeManager->getStorage($entityType);

  try {
    $storage->save($entity);
  }
  catch (\Exception $e) {
    /** @var \Drupal\Core\Messenger\MessengerInterface $messenger */
    $messenger = \Drupal::service(MessengerInterface::class);
    $messenger->addError(t('Error updating the entity. Please try again.'));
    return;
  }

  /** @var \Drupal\Core\Messenger\MessengerInterface $messenger */
  $messenger = \Drupal::service(MessengerInterface::class);
  $messenger->addStatus(t('Meta tags updated'));

  $destination = \Drupal::request()->query->get('destination');
  $form_state->setRedirect($destination ?: '<front>');
}

/**
 * Display all paths that have defined meta tags.
 *
 * @param mixed $form
 * @param mixed $form_state
 */
function metatags_quick_admin_path_based($form, $form_state) {
  // Get current language and module path.
  global $language;
  $module_path = \Drupal::service('extension.list.module')->getPath('metatags_quick');
  // Grab language list.
  $languages = _metatags_quick_language_list();
  // Create table form.
  $form['new_path_based'] = [
    '#type' => 'fieldset',
    '#title' => t('New path'),
    '#collapsible' => FALSE,
    '#attached' => [
      'js' => [$module_path . '/js/admin.js'],
      'css' => [$module_path . '/css/admin.css'],
    ],
    'new_path' => [
      '#type' => 'container',
      '#prefix' => '<div style="float:left">',
      '#suffix' => '</div><div style="clear:both;"> </div>',
      'path' => [
        '#type' => 'textfield',
        '#title' => t('Path:'),
        '#maxlength' => 255,
        '#description' => t('Enter path starting without a leading "/". "*" can be used as a wildcard at the end of a path.'),
        '#prefix' => '<div style="float:left;">',
        '#suffix' => '</div>',
      ],
      'language' => [
        '#type' => 'select',
        '#title' => t('Select language'),
        '#options' => $languages,
        '#default_value' => $language->language,
        '#prefix' => '<div style="float:left; margin-left: 40px;">',
        '#suffix' => '</div><div style="clear:both;"> </div>',
      ],
      'new_path_submit' => [
        '#type' => 'submit',
        '#value' => t('Create'),
        '#attributes' => ['style' => 'margin-bottom: 20px;'],
      ],
    ],
  ];
  $form['path_based'] = [
    '#type' => 'fieldset',
    '#title' => t('Manage Paths'),
    '#collapsible' => FALSE,
  ];
  $header = [
    'path' => ['data' => t('Path'), 'field' => 'p.path'],
    'language' => ['data' => t('Language'), 'field' => 'p.lang', 'width' => '10%'],
    'operations' => ['data' => t('Operations'), 'width' => '30%', 'colspan' => 2],
  ];
  // @todo Drupal Rector Notice: Please delete the following comment after you've made any necessary changes.
  // You will need to use `\Drupal\core\Database\Database::getConnection()` if you do not yet have access to the container here.
  $query = \Drupal::database()->select('metatags_quick_path_based', 'p')->extend('PagerDefault')->extend('TableSort');
  $result = $query
    ->fields('p')
    ->limit(50)
    ->orderByHeader($header)
    ->execute();
  // Set up to fill options array.
  $destination = \Drupal::service('redirect.destination')->get();
  $options = [];
  // Fill options array.
  foreach ($result as $path) {
    $options[] = [
      'path' => $path->path,
      'language' => $languages[$path->lang],
      'edit' => Link::fromTextAndUrl(t('Edit'), Url::fromUri('internal:/admin/config/search/metatags_quick/path_based/edit', [
        'query' => [
          'pid' => $path->id,
          'destination' => $destination['destination'],
        ],
      ])),
      'delete' => Link::fromTextAndUrl(t('Delete'), Url::fromUri('internal:/admin/config/search/metatags_quick/path_based/delete', [
        'query' => [
          'pid' => $path->id,
          'destination' => $destination['destination'],
        ],
      ])),
    ];
  }
  // Add created table.
  $form['path_based']['existing'] = [
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $options,
    '#empty' => t('No content available.'),
    '#attributes' => ['id' => 'path_based'],
  ];
  // Add default page.
  $form['path_based']['pager'] = ['#markup' => theme('pager', ['tags' => NULL])];
  // Return listing form.
  return $form;
}

/**
 * Validates the existance of a valid path provided by the user. Path has to be
 * at least 2 characters long.
 *
 * @param mixed $form
 * @param mixed $form_state
 */
function metatags_quick_admin_path_based_validate($form, $form_state) {
  if (isset($form_state['values']['path'])) {
    // Create path and empty entity.
    if (strlen(trim($form_state['values']['path'])) < 2) {
      \Drupal::messenger()->addError('path', t('Illegal path entered.'));
    }
  }
}

/**
 * Handles the creation of a new path by redirecting to
 * metatags_quick_admin_path_based_edit() which autocreates new
 * entities if they don't exist yet for a given path and language.
 *
 * @param mixed $form
 * @param mixed $form_state
 */
function metatags_quick_admin_path_based_submit($form, &$form_state) {
  if (isset($form_state['values']['path'])) {
    // Redirect to existing form.
    $destination = \Drupal::service('redirect.destination')->get();
    ;
    $form_state['redirect'] = [
      'admin/config/search/metatags_quick/path_based/edit',
      [
        'query' => [
          'lang' => Html::escape($form_state['values']['language']),
          'path' => Html::escape($form_state['values']['path']),
          'destination' => $destination['destination'],
        ],
      ],
    ];
  }
}

/**
 * Displays a form to the user allowing him to edit the path and all the fields
 * of the metatag entity associated with that path
 *
 * @param array $form
 * @param array $form_state
 */
function metatags_quick_admin_path_based_edit($form, &$form_state) {
  $controller = \Drupal::service('entity_type.manager')->getStorage('metatags_path_based');
  if (isset($_GET['pid'])) {
    $entity_id = (int) $_GET['pid'];
  }
  else {
    // @todo Drupal Rector Notice: Please delete the following comment after you've made any necessary changes.
    // You will need to use `\Drupal\core\Database\Database::getConnection()` if you do not yet have access to the container here.
    $entity_id = \Drupal::database()->select('metatags_quick_path_based', 'm')
      ->fields('m', ['id'])
      ->condition('lang', Html::escape($_GET['lang']))
      ->condition('path', Html::escape($_GET['path']))
      ->execute()
      ->fetchField();
  }
  if (!$entity_id) {
    // @todo Drupal Rector Notice: Please delete the following comment after you've made any necessary changes.
    // You will need to use `\Drupal\core\Database\Database::getConnection()` if you do not yet have access to the container here.
    $entity_id = \Drupal::database()->insert('metatags_quick_path_based')
      ->fields(['lang' => Html::escape($_GET['lang']), 'path' => Html::escape($_GET['path'])])
      ->execute();
    $entity = new stdClass();
    $entity->id = $entity_id;
    $entity->lang = Html::escape($_GET['lang']);
    $entity->path = Html::escape($_GET['path']);
  }
  else {
    $entities = $controller->load([$entity_id]);
    $entity = $entities[$entity_id];
  }

  $form_state['entity'] = $entity;
  $entityFormValidator = \Drupal::service(EntityFormValidatorInterface::class);
  $entityFormValidator->validateFormFields('metatags_path_based', $entity, $form, $form_state, LANGUAGE_NONE);
  $form['entity_id'] = [
    '#type' => 'hidden',
    '#value' => $entity_id,
  ];
  $form['path'] = [
    '#type' => 'textfield',
    '#title' => t('Edit path'),
    '#description' => t('Enter path starting without a leading "/". "*" can be used as a wildcard at the end of a path.'),
    '#default_value' => html_entity_decode($entity->path),
    '#maxlength' => 255,
    '#weight' => '-50',
  ];
  $form['lang'] = [
    '#title' => t('Edit language'),
    '#type' => 'select',
    '#options' => _metatags_quick_language_list(),
    '#default_value' => $entity->lang,
    '#weight' => '-40',
  ];
  $form['submit'] = [
    '#value' => t('Submit'),
    '#type' => 'submit',
    '#weight' => '49',
  ];
  $form['cancel'] = [
    '#type' => 'submit',
    '#value' => t('Cancel'),
    '#weight' => 20,
    '#submit' => ['metatags_quick_admin_path_based_edit_cancel'],
    '#weight' => '50',
  ];
  return $form;
}

/**
 * Returns back to the metatags listing.
 *
 * @param mixed $form
 * @param mixed $form_state
 */
function metatags_quick_admin_path_based_edit_cancel($form, &$form_state) {
  if (isset($_GET['destination'])) {
    $form_state['redirect'] = $_GET['destination'];
  }
}

/**
 * Checks if the user has submitted a valid path. Path must be at least 2
 * characters long
 *
 * @param mixed $form
 * @param mixed $form_state
 */
function metatags_quick_admin_path_based_edit_validate(array &$form, FormStateInterface $form_state) {
  $messenger = \Drupal::messenger();
  $fieldValidation = \Drupal::service(FieldValidationInterface::class);

  if ($form_state->hasValue('path')) {
    $pathValue = $form_state->getValue('path');
    // Create path and empty entity.
    if (strlen(trim($pathValue)) < 2) {
      $messenger->addError(t('Illegal path entered.'));
    }
  }

  // Get the entity from the form state.
  $entity = $form_state->getFormObject()->getEntity();

  // Validate the fields of the entity.
  foreach ($entity->getFieldDefinitions() as $fieldDefinition) {
    if ($fieldDefinition instanceof FieldDefinitionInterface) {
      $fieldItems = $entity->get($fieldDefinition->getName());
      if ($fieldItems instanceof FieldItemListInterface) {
        $fieldValidation->validate($fieldItems, $form_state);
      }
    }
  }
}

/**
 * Updates the metatags entity for a given path after the user has submitted the
 * form. Also updates the path if it has been altered.
 *
 * @param mixed $form
 * @param mixed $form_state
 */
function metatags_quick_admin_path_based_edit_submit($form, &$form_state, EntityTypeInterface $entityType) {
  // Abort if there is no valid entity.
  if (!$form_state['entity']) {
    \Drupal::messenger()->addError(t('Wrong path'));
    return;
  }
  // Update path if it has been altered.
  if ($form_state['values']['path'] != html_entity_decode($form_state['entity']->path)
    || $form_state['values']['lang'] != $form_state['entity']->lang) {
    // Check if there isn't already a path like the new path.
    // @todo Drupal Rector Notice: Please delete the following comment after you've made any necessary changes.
    // You will need to use `\Drupal\core\Database\Database::getConnection()` if you do not yet have access to the container here.
    $entity_id = \Drupal::database()->select('metatags_quick_path_based', 'm')
      ->fields('m', ['id'])
      ->condition('lang', Html::escape($form_state['values']['lang']))
      ->condition('path', Html::escape($form_state['values']['path']))
      ->execute()
      ->fetchField();
    // If not continue.
    if (!$entity_id) {
      // @todo Drupal Rector Notice: Please delete the following comment after you've made any necessary changes.
      // You will need to use `\Drupal\core\Database\Database::getConnection()` if you do not yet have access to the container here.
      \Drupal::database()->update('metatags_quick_path_based')
        ->fields([
          'path' => Html::escape(trim($form_state['values']['path'])),
          'lang' => $form_state['values']['lang'],
        ])
        ->condition('id', $form_state['entity']->id)
        ->execute();
    }
    else {
      // Otherwise abort with error message.
      \Drupal::messenger()->addError('path', t('Another set of meta tags exists for this path and language'));
      return;
    }
  }
  // Update entity fields.
  $entity = $form_state['entity'];
  $entityFormBuilder = \Drupal::service(EntityFormBuilderInterface::class);

  // Build and submit the entity form.
  $entityFormBuilder->submitForm($entityType, $form, $form_state);
  $entity->save('metatags_path_based');
  // Display message and redirect.
  \Drupal::messenger()->addStatus('Meta tags updated');
  if (isset($_GET['destination'])) {
    $form_state['redirect'] = $_GET['destination'];
  }
  else {
    $form_state['redirect'] = FALSE;
  }
}

/**
 * Display a delete confirmation for the user allowing him to choose to proceed
 * or abort the removal.
 *
 * @param mixed $form
 * @param mixed $form_state
 */
function metatags_quick_admin_path_based_delete($form, &$form_state) {
  // Delete confirmation.
  if (isset($_GET['pid'])) {
    $pid = (int) $_GET['pid'];
    $controller = \Drupal::service('entity_type.manager')->getStorage('metatags_path_based');
    ;
    $entities = $controller->load([$pid]);

    if (empty($entities)) {
      $form['intro'] = [
        '#markup' => t('Path not found'),
      ];
      return $form;
    }

    $path_object = $entities[$pid];
    $form_state['#path_object'] = $path_object;

    $form['intro'] = [
      '#type' => 'item',
      '#markup' => t('Do you really want to delete the following path:'),
    ];

    $form['item'] = [
      '#type' => 'item',
      '#markup' => htmlspecialchars_decode($path_object->path) . '(' . $path_object->lang . ')',
      '#prefix' => '<ul><li>',
      '#suffix' => '</ul></li>',
    ];
    $form['note'] = [
      '#type' => 'item',
      '#markup' => t('This action cannot be undone.'),
    ];
    $form['actions'] = [
      '#type' => 'actions',
      'delete' => [
        '#type' => 'submit',
        '#value' => t('Delete'),
        '#submit' => ['metatags_quick_admin_path_based_delete_submit'],
      ],
      'cancel' => [
        '#type' => 'submit',
        '#value' => t('Cancel'),
        '#limit_validation_errors' => [],
        '#submit' => ['metatags_quick_admin_path_based_delete_cancel'],
      ],
    ];
    return $form;
  }
}

/**
 * Deletion has been confirmed. Item will be deleted if it is a valid one.
 *
 * @param mixed $form
 * @param mixed $form_state
 */
function metatags_quick_admin_path_based_delete_submit($form, &$form_state) {
  metatags_path_based_delete($form_state['#path_object']->id);
}

/**
 * Cancels the deletion and should return to the listing.
 *
 * @param mixed $form
 * @param mixed $form_state
 */
function metatags_quick_admin_path_based_delete_cancel($form, &$form_state) {
  if (isset($_GET['destination'])) {
    $form_state['redirect'] = $_GET['destination'];
  }
}

/**
 * Creates a select list compatible list of languages keyed by language tags and
 * with localized language values.
 *
 * @global type $language
 *
 * @return array $languages
 */
function _metatags_quick_language_list() {
  $languageManager = \Drupal::service(LanguageManagerInterface::class);
  global $language;
  $languages = $languageManager->getLanguages();
  foreach ($languages as $lang) {
    $languages[$lang->language] = t($lang->name);
  }
  return $languages;
}

/**
 * Delete path-based meta tags.
 *
 * @param object $entity
 */
function metatags_path_based_delete($entity) {
  if (!is_object($entity)) {
    $controller = \Drupal::service('entity_type.manager')->getStorage('metatags_path_based');
    ;
    // @todo Drupal Rector Notice: Please delete the following comment after you've made any necessary changes.
    // You will need to use `\Drupal\core\Database\Database::getConnection()` if you do not yet have access to the container here.
    $entity = \Drupal::database()->select('metatags_quick_path_based', 'm')
      ->fields('m', ['id'])
      ->condition('id', (int) $entity)
      ->execute()
      ->fetchField();
    if ($entity) {
      $values = array_values(\Drupal::service('entity_type.manager')->getStorage('metatags_path_based')->load([$entity]));
      $entity = array_pop($values);
    }
  }
  if (!$entity || !is_object($entity) || !isset($entity->path)) {
    return FALSE;
  }
  // Do the deletion.
  // @todo Drupal Rector Notice: Please delete the following comment after you've made any necessary changes.
  // You will need to use `\Drupal\core\Database\Database::getConnection()` if you do not yet have access to the container here.
  \Drupal::database()->delete('metatags_quick_path_based')
    ->condition('id', $entity->id)
    ->execute();
  \Drupal::messenger()->addStatus(t('Deleted path-based meta tags for @path', ['@path' => $entity->path]));
}

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

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