Skip to content

Instantly share code, notes, and snippets.

@DanLaufer
Last active June 12, 2019 15:27
Show Gist options
  • Save DanLaufer/c42c4adfa88bbe747b1b47b07863d3af to your computer and use it in GitHub Desktop.
Save DanLaufer/c42c4adfa88bbe747b1b47b07863d3af to your computer and use it in GitHub Desktop.
Drupal 8 - Edit This Node button
name: Edit This Node
description: Adds a button to the toolbar to edit the current node. It will say "New Draft" if using moderation.
package: Custom
type: module
version: 1.0
core: 8.x
<?php
// use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
/**
* Implements hook_toolbar().
*/
function edit_this_node_toolbar() {
$items = [];
// Inject the "Edit" (or "New Draft") local task into the toolbar
$manager = \Drupal::service('plugin.manager.menu.local_task');
$links = $manager->getLocalTasks(\Drupal::routeMatch()->getRouteName(), 0);
if (!empty($links)) {
$local_links = [];
foreach ($links['tabs'] as $route => $link) {
$local_links[$route] = $link['#link'];
}
foreach ($local_links as $route => $content) {
if($route === 'entity.node.edit_form' && isset($content['title'])) {
$items['edit_this_node'] = [
'#type' => 'toolbar_item',
'tab' => [
'#type' => 'link',
'#title' => 'Edit Node ' . $content['url']->getRouteParameters()['node'],
'#url' => Url::fromRoute('entity.node.edit_form', $content['url']->getRouteParameters()),
'#attributes' => [
'title' => t('Edit This Node'),
'class' => [
'toolbar-icon',
'toolbar-icon-edit',
],
],
'#cache' => [
'contexts' => [
// Cacheable per user, because the current user's name is shown.
'url',
],
],
],
];
}
}
}
return $items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment