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)?
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With