pate-1.0.0/pate.module

pate.module
<?php

/**
 * @file
 * Contains pate hooks.
 */

use Drupal\Core\Config\Entity\ThirdPartySettingsInterface;
use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\node\Entity\NodeType;
use Drupal\node\NodeInterface;
use Drupal\pate\Access\PateNodeAccessHandler;
use Drupal\pate\Form\PateTemplatizeForm;

/**
 * Implements hook_entity_base_field_info().
 */
function pate_entity_base_field_info(EntityTypeInterface $entity_type) {
  // Add our flag basefield to all nodes.
  $fields = [];
  if ($entity_type->id() === 'node') {
    $fields['pate_is_template'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Is template'))
      ->setDescription(t('A flag indicating whether this node has been marked as a page template.'))
      ->setRevisionable(TRUE)
      ->setTranslatable(FALSE)
      ->setDefaultValue(FALSE)
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', FALSE);
    $fields['pate_structure_only'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Structure only'))
      ->setDescription(t('A flag indicating whether this template should be cloned using structure-only mode.'))
      ->setRevisionable(TRUE)
      ->setTranslatable(FALSE)
      ->setDefaultValue(FALSE)
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', FALSE);
  }
  return $fields;
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function pate_form_node_type_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $type = $form_state->getFormObject()->getEntity();
  assert($type instanceof NodeType);

  $settings = $type->getThirdPartySettings('pate');
  $form['pate'] = [
    '#type' => 'details',
    '#title' => t('Page Templates'),
    '#tree' => TRUE,
  ];
  if (isset($form['additional_settings']) && $form['additional_settings']['#type'] === 'vertical_tabs') {
    $form['pate']['#group'] = 'additional_settings';
  }
  $form['pate']['is_templatable'] = [
    '#type' => 'checkbox',
    '#title' => t('Allow converting into page template'),
    '#description' => t('If checked, admins will be able to convert nodes of this type into page templates.'),
    '#default_value' => $settings['is_templatable'] ?? NULL,
  ];

  // If there are nodes already converted into templates, make sure admins
  // can't mark this as non-templatable anymore.
  $count = \Drupal::entityQuery('node')
    ->condition('type', $type->id())
    ->condition('pate_is_template', TRUE)
    ->accessCheck(FALSE)
    ->count()
    ->execute();
  if (!empty($count)) {
    $form['pate']['is_templatable']['#disabled'] = TRUE;
    $form['pate']['is_templatable']['#description'] .= t('<em>This option cannot be unchecked since there are existing templates of this type.</em>');
  }

  $form['#entity_builders'][] = 'pate_entity_builder';
}

/**
 * Additional entity builder callback for our node type forms.
 *
 * @see pate_form_node_type_form_alter()
 */
function pate_entity_builder($entity_type, ThirdPartySettingsInterface $type, array &$form, FormStateInterface $form_state) {
  $pate_values = $form_state->getValue('pate');
  foreach ($pate_values as $key => $value) {
    $type->setThirdPartySetting('pate', $key, $value);
  }
}

/**
 * Implements hook_entity_type_build().
 */
function pate_entity_type_build(array &$entity_types) {
  // Add our Templatize form class and link template to node entities.
  assert($entity_types['node'] instanceof ContentEntityTypeInterface);
  $entity_types['node']->setFormClass('templatize', PateTemplatizeForm::class);
  $entity_types['node']->setLinkTemplate('templatize', $entity_types['node']->getLinkTemplate('canonical') . '/templatize');
}

/**
 * Implements hook_entity_type_alter().
 */
function pate_entity_type_alter(array &$entity_types) {
  // Set a custom access handler to nodes.
  $entity_types['node']->setHandlerClass('access', PateNodeAccessHandler::class);
}

/**
 * Implements hook_theme().
 */
function pate_theme($existing, $type, $theme, $path) {
  return [
    'pate_templates_list' => [
      'variables' => [
        'add_new_url' => NULL,
        'add_new_label' => NULL,
        'templates' => NULL,
      ],
    ],
    'pate_templates_template' => [
      'variables' => [
        'title' => NULL,
        'create_from_template_label' => NULL,
        'create_from_template_url' => NULL,
        'preview_label' => NULL,
        'preview_url' => NULL,
      ],
    ],
    'pate_template_preview' => [
      'variables' => [
        'node' => NULL,
        'node_view_url' => NULL,
        'create_from_template_label' => NULL,
        'create_from_template_url' => NULL,
      ],
    ],
  ];
}

/**
 * Implements hook_page_attachments().
 */
function pate_page_attachments(array &$attachments) {
  $is_pate_template = (bool) \Drupal::request()->query->get('pate-template-id');
  if ($is_pate_template) {
    $attachments['#attached']['library'][] = 'pate/template_preview.iframe';
    // Remove the toolbar from the DOM.
    $to_remove = [
      '#toolbar-administration',
      '#toolbar-bar',
    ];
    // Allow modules have a say in this list of elements to remove.
    \Drupal::moduleHandler()->alter('pate_template_elements_remove', $to_remove);
    $attachments['#attached']['drupalSettings']['pate']['template_elements_to_remove'] = $to_remove;
  }
}

/**
 * Implements hook_menu_links_discovered_alter().
 */
function pate_menu_links_discovered_alter(&$links) {
  $templates_bundles = \Drupal::database()
    ->query("SELECT DISTINCT type FROM {node_field_data} WHERE pate_is_template=1")
    ->fetchCol();
  if (empty($templates_bundles)) {
    return;
  }
  foreach ($templates_bundles as $type) {
    $content_type = \Drupal::entityTypeManager()->getStorage('node_type')->load($type);
    if (!$content_type) {
      continue;
    }
    if (!empty($links["admin_toolbar_tools.extra_links:node.add.{$type}"])) {
      // Alter the "Add %type" link to point to our templates list.
      $links["admin_toolbar_tools.extra_links:node.add.{$type}"]['route_name'] = 'pate.templates_for_type';
    }
  }
}

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function pate_node_presave(EntityInterface $entity) {
  assert($entity instanceof NodeInterface);
  if ($entity->hasField('pate_is_template')
    && !empty($entity->original->pate_is_template)
    && $entity->original->pate_is_template->value != $entity->pate_is_template->value) {
    // When a node has the "pate_is_template" field changed, we need to rebuild
    // menu links discovery. This needs to be a shutdown function since we want
    // the node with new values to be fully saved when the menu is rebuilt.
    // Unfortunately this means editors will need an additional page refresh to
    // the the new items in the menu.
    // @todo Investigate if there are better approaches to avoid this.
    drupal_register_shutdown_function('_pate_shutdown_rebuild_router_caches');
  }
}

/**
 * Implements hook_ENTITY_TYPE_delete().
 */
function pate_node_delete(EntityInterface $entity) {
  assert($entity instanceof NodeInterface);
  if ($entity->hasField('pate_is_template')
    && $entity->pate_is_template->value == TRUE) {
    // Similar to what we do in pate_node_presave(), when a template is deleted
    // we want to remove its link from the menu.
    drupal_register_shutdown_function('_pate_shutdown_rebuild_router_caches');
  }
}

/**
 * Helper to trigger a menu router rebuild as a shutdown function.
 */
function _pate_shutdown_rebuild_router_caches() {
  \Drupal::service('router.builder')->rebuild();
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function pate_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // On new node forms, add an extra "Create from template" button at the
  // top, in case there are templates for this node type.
  $node = $form_state->getFormObject()->getEntity();
  assert($node instanceof NodeInterface);
  if ($node->isNew()) {
    $results = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->getQuery()
      ->condition('pate_is_template', TRUE)
      ->condition('type', $node->bundle())
      ->accessCheck(TRUE)
      ->range(0, 1)
      ->execute();
    if (!empty($results)) {
      $url = Url::fromRoute('pate.templates_for_type', ['node_type' => $node->bundle()]);
      $form['pate_create_from_template'] = [
        '#markup' => '<a class="button" href="' . $url->toString() . '">' . t('Create from template') . '</a>',
        '#weight' => '-299',
      ];
    }
  }
}

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

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