Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 8 - How to add task and contextual links for specific node type?

Tags:

drupal

I created a task link and a contextual one for base_route: entity.node.canonical

mymodule.routing.yml

mymodule.mycustomroute:
  path: '/node/{node}/custom-path'
  defaults:
    _form: '\Drupal\mymodule\Form\MyForm'
  requirements:
    _permission: 'my permission'
    node: '[0-9]+'

mymodule.links.tasks.yml

mymodule.mycustomroute:
  route_name: mymodule.mycustomroute
  base_route: entity.node.canonical
  title: 'my title'

mymodule.links.contextual.yml

mymodule.mycustomroute:
  route_name: mymodule.mycustomroute
  group: node

My link shows up next to View / Edit / Delete links on each node as I wanted.

Now I am wondering how is it possible to make these links available only for specific node type(s)?

like image 820
MacSim Avatar asked Apr 08 '16 10:04

MacSim


1 Answers

mymodule/mymodule.routing.yml :

mymodule.mycustomroute:
  path: '/node/{node}/custom-path'
  defaults:
    _form: '\Drupal\mymodule\Form\MyForm'
  requirements:
    _permission: 'my permission'
    _custom_access: '\Drupal\mymodule\Access\NodeTypeAccessCheck::access'
    _node_types: 'node_type_1,node_type_2,node_type_n'
    node: '\d+'

mymodule/src/Access/NodeTypeAccessCheck.php :

namespace Drupal\mymodule\Access;

use Drupal\Core\Access\AccessCheckInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;
use Symfony\Component\Routing\Route;

/**
 * Check the access to a node task based on the node type.
 */
class NodeTypeAccessCheck implements AccessCheckInterface {

  /**
   * {@inheritdoc}
   */
  public function applies(Route $route) {
    return NULL;
  }

  /**
   * A custom access check.
   *
   * @param \Drupal\node\NodeInterface $node
   *   Run access checks for this node.
   */
  public function access(Route $route, NodeInterface $node) {
    if ($route->hasRequirement('_node_types')) {
      $allowed_node_types = explode(',', $route->getRequirement('_node_types'));
      if (in_array($node->getType(), $allowed_node_types)) {
        return AccessResult::allowed();
      }
    }
    return AccessResult::forbidden();
  }

}
like image 90
MacSim Avatar answered Sep 28 '22 03:09

MacSim