When you define a route URL, you can add parameters by name to be sent to the display method. These parameters are wrapped in braces, for example, /node/add/{node_type}. The values passed in via the URL are passed to the controller by name, so the name of the variable in the controller function needs to be the same name as the parameter in the URL. The order of the parameters in the function signature doesn't matter, only that they are named the same.
So, if we changed the route URL to mastering_drupal_8/test/{message}, we would change the controller function to:
public function test($message) {
return [
'#type' => 'markup',
'#markup' => $this->t("Test: " . $message),
];
}
Named parameters are not sanitized by default. You need to sanitize them in your controller before using them. Named parameters are also required initially. In our example above, if you don't provide a value for the message, you will receive a 404 Page Not Found error. You add attributes matching the parameter name in the defaults section of the routing YAML file. For example:
mastering_drupal_8.test_page_message:
path: 'mastering_drupal_8/message/{message}'
defaults:
_controller:
'\Drupal\mastering_drupal_8\Controller\TestPageController::testMessage'
message: 'foo'
requirements:
_access: 'TRUE'
If the named parameter is the name of an entity, it will be loaded prior to it being sent to the controller. Changing the routing YAML file to:
mastering_drupal_8.test_page_node:
path: 'mastering_drupal_8/node/{node}'
defaults:
_controller:
'\Drupal\mastering_drupal_8\Controller\TestPageController::testNode'
requirements:
_access: 'TRUE'
Would change the controller function to:
public function test(NodeInterface $node) {
return [
'#type' => 'markup',
'#markup' => $this->t("Test: " . $node->getTitle()),
];
}
When using the entity lookup parameter, if the entity fails to load, Drupal will return a 404 Page Not Found error. Your code will be guaranteed to receive an actual entity interface.