Skip to content

Instantly share code, notes, and snippets.

@jerbob92
Created October 27, 2015 13:29
Show Gist options
  • Save jerbob92/fa4aec90f58937a88df5 to your computer and use it in GitHub Desktop.
Save jerbob92/fa4aec90f58937a88df5 to your computer and use it in GitHub Desktop.
Drupal 8 Derative Menu Link Example
<?php
/**
* @file
* Contains \Drupal\mymodule\Plugin\Derivative\MyModuleMenuLinkDerivative.
*/
namespace Drupal\mymodule\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\node\Entity\Node;
/**
* Provides menu links of all Node entities with type "Page".
*/
class MyModuleMenuLinkDerivative extends DeriverBase implements ContainerDeriverInterface {
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static();
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
$links = array();
// Get all nodes of type page.
$nodeQuery = \Drupal::entityQuery('node');
$nodeQuery->condition('type', 'page');
$nodeQuery->condition('status', TRUE);
$ids = $nodeQuery->execute();
$ids = array_values($ids);
$nodes = Node::loadMultiple($ids);
foreach($nodes as $node) {
$links['mymodule_menulink_' . $node->id()] = [
'title' => $node->get('title')->getString(),
'menu_name' => 'main',
'route_name' => 'entity.node.canonical',
'route_parameters' => [
'node' => $node->id(),
],
] + $base_plugin_definition;
}
return $links;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment