Skip to content

Instantly share code, notes, and snippets.

@jerbob92
Created March 23, 2017 14:12
Show Gist options
  • Save jerbob92/51128ab3106ff49533625a237fe8bb2e to your computer and use it in GitHub Desktop.
Save jerbob92/51128ab3106ff49533625a237fe8bb2e to your computer and use it in GitHub Desktop.
Creating default pages in Drupal 8
<?php
use Drupal\node\Entity\Node;
$current_language = \Drupal::languageManager()->getCurrentLanguage();
$default_pages = \Drupal::state()->get('my_module.default_pages', array());
$node_id = (isset($default_pages['front_' . $current_language->getId()]) ? $default_pages['front_' . $current_language->getId()] : NULL);
if (!$node_id) {
return NULL;
}
$node = Node::load($node_id);
<?php
/**
* Return node of current language so metatag attaches metatags.
*
* @param \Drupal\Core\Routing\CurrentRouteMatch $route
* @return \Drupal\Core\Entity\EntityInterface|null
*/
function my_front_module_metatag_route_entity($route) {
if ($route && $route->getRouteName() == 'my_front_module.front') {
return \Drupal\my_front_module\Controller\FrontController::getFrontPageForCurrentLanguage();
}
}
my_front_module.front:
path: '/front'
defaults:
_controller: '\Drupal\my_front_module\Controller\FrontController::content'
_title_callback: '\Drupal\my_front_module\Controller\FrontController::title'
requirements:
_permission: 'access content'
services:
my_front_module.default_pages_subscriber:
class: '\Drupal\my_front_module\EventSubscriber\DefaultPagesSubscriber'
tags:
- { name: 'event_subscriber' }
<?php
namespace Drupal\my_front_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;
class FrontController extends ControllerBase {
/**
* @return \Drupal\Core\Language\LanguageInterface
*/
private static function currentLanguage() {
$language_manger = \Drupal::languageManager();
return $language_manger->getCurrentLanguage();
}
/**
* @return \Drupal\Core\Entity\EntityInterface
*/
public static function getFrontPageForCurrentLanguage() {
$current_language = self::currentLanguage();
$default_pages = \Drupal::state()->get('my_front_module.default_pages', array());
$node_id = (isset($default_pages['front_' . $current_language->getId()]) ? $default_pages['front_' . $current_language->getId()] : NULL);
if (!$node_id) {
return NULL;
}
$node = Node::load($node_id);
if (!$node) {
return NULL;
}
return $node;
}
public function title() {
$node = $this->getFrontPageForCurrentLanguage();
if (!$node) {
return '';
}
return $node->label();
}
public function content() {
$node = $this->getFrontPageForCurrentLanguage();
if (!$node) {
return array(
'#type' => 'markup',
'#markup' => t('Frontpage not found!'),
);
}
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$build = $view_builder->view($node, 'default');
return $build;
}
}
<?php
/**
* @file
* Contains \Drupal\my_front_module\EventSubscriber\DefaultPagesSubscriber.
*/
namespace Drupal\my_front_module\EventSubscriber;
use Drupal\my_module\EventSubscriber\DefaultPagesBase;
/**
* Event Subscriber DefaultPageSubscriber.
*/
class DefaultPagesSubscriber extends DefaultPagesBase {
/**
* {@inheritdoc}
*/
protected function getDefaultPages() {
$frontpage_base = [
'type' => 'page',
'path' => 'home',
'title' => 'Home',
];
return [
'frontpage_nl' => $frontpage_base + [
'field_description' => 'Dit is de voorpagina!',
],
'frontpage_en' => $frontpage_base + [
'field_description' => 'This is the frontpage!',
],
'frontpage_de' => $frontpage_base + [
'field_description' => 'Dies ist die Titelseite!',
],
];
}
}
<?php
/**
* Implements hook_drush_command().
*/
function my_module_drush_command() {
$items = array();
$items['default-pages'] = [
'description' => 'Installs the default pages and registers them in configuration.',
'arguments' => [],
'drupal dependencies' => ['my_module'],
'aliases' => [],
];
return $items;
}
/**
* Callback function for default pages.
*/
function drush_my_module_default_pages() {
drush_print('Ensuring default pages:');
/** @var Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher $dispatcher */
$dispatcher = \Drupal::service('event_dispatcher');
$dispatcher->dispatch('my_module.default_pages');
}
<?php
use Drupal\Core\Access\AccessResult;
/**
* Implements hook_node_access().
*
* Makes sure default pages nodes aren't deleted.
*/
function my_module_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
if ($op == 'delete') {
$default_pages = \Drupal::state()->get('my_module.default_pages', array());
$default_pages_nids = array_flip($default_pages);
if (isset($default_pages_nids[$node->id()])) {
// Return forbidden when this is a default page.
return AccessResult::forbidden();
}
}
// No opinion by default.
return AccessResult::neutral();
}
<?php
/**
* @file
* Contains \Drupal\my_module\EventSubscriber\DefaultPagesBase.
*/
namespace Drupal\my_module\EventSubscriber;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\node\Entity\Node;
use Drupal\Core\Language\LanguageInterface;
/**
* Event Subscriber DefaultPageSubscriber.
*/
abstract class DefaultPagesBase implements EventSubscriberInterface {
public static $stateKey = 'my_module.default_pages';
public function onCreateDefaultPages(Event $event) {
$default_pages = $this->getDefaultPages();
if (count($default_pages)) {
foreach ($default_pages as $id => $default_page) {
if ($this->defaultPageExists($id)) {
drush_print($id . ': Page already exists!');
continue;
}
if ($this->createDefaultPage($id, $default_page)) {
drush_print($id . ': Page created!');
}
else {
drush_set_error($id . ': Error while creating page!');
}
}
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events['my_module.default_pages'][] = ['onCreateDefaultPages'];
return $events;
}
/**
* @return array
*/
abstract protected function getDefaultPages();
/**
* @param $id
* @return bool
*/
private function defaultPageExists($id) {
$default_pages = \Drupal::state()->get(self::$stateKey, array());
$entity_id = (isset($default_pages[$id]) ? $default_pages[$id] : NULL);
if ($entity_id && $node = Node::load($entity_id)) {
return TRUE;
}
return FALSE;
}
/**
* @param $id
* @param $page
* @return bool
*/
private function createDefaultPage($id, $page) {
if (!isset($page['langcode'])) {
$page['langcode'] = LanguageInterface::LANGCODE_NOT_SPECIFIED;
}
$path = FALSE;
if (isset($page['path'])) {
$path = $page['path'];
unset($page['path']);
}
try {
$node = Node::create($page);
$node->save();
if ($path) {
/* @var \Drupal\Core\Path\AliasStorageInterface $path_storage */
$path_storage = \Drupal::service('path.alias_storage');
$saved_path = $path_storage->save("/node/" . $node->id(), '/' . $path, $page['langcode']);
}
/* @var \Drupal\Core\Config\ConfigFactoryInterface $config */
$default_pages = \Drupal::state()->get(self::$stateKey, array());
$default_pages[$id] = $node->id();
\Drupal::state()->set(self::$stateKey, $default_pages);
return TRUE;
}
catch (\Exception $e) {
drush_set_error('Error while creating default page:');
drush_set_error($e->getMessage());
}
return FALSE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment