Skip to content

Instantly share code, notes, and snippets.

@levmyshkin
Created November 19, 2021 13:42
Show Gist options
  • Save levmyshkin/e8da2be8517b6aa73dc68c78aa566cc8 to your computer and use it in GitHub Desktop.
Save levmyshkin/e8da2be8517b6aa73dc68c78aa566cc8 to your computer and use it in GitHub Desktop.
Drupal Route with parameter
<?php
//modules/custom/drupalbook/src/Controller/DisplayNode.php
namespace Drupal\drupalbook\Controller;
use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;
/**
* Provides route responses for the DrupalBook module.
*/
class DisplayNode {
/**
* Returns a simple page.
*
* @return array
* A simple renderable array.
*/
public function content(NodeInterface $node) {
$element = array(
'#markup' => $node->body->value,
);
return $element;
}
/**
* Checks access for this controller.
*/
public function access(NodeInterface $node) {
$user = \Drupal::currentUser();
if ($node->getType() == 'article' && !in_array('authenticated', $user->getRoles())) {
return AccessResult::forbidden();
}
return AccessResult::allowed();
}
/**
* Returns a page title.
*/
public function getTitle(NodeInterface $node) {
return $node->getTitle();
}
}
name: DrupalBook
description: Custom module for learning Drupal
type: module
core: 8.x
core_version_requirement: ^8 || ^9
package: DrupalBook
drupalbook.display_node:
path: '/display-node/{node}'
defaults:
_controller: '\Drupal\drupalbook\Controller\DisplayNode::content'
_title_callback: '\Drupal\drupalbook\Controller\DisplayNode::getTitle'
requirements:
_custom_access: '\Drupal\drupalbook\Controller\DisplayNode::access'
options:
parameters:
node:
type: entity:node
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment