Arg Function: How to Replace It in Drupal 8

3 min read

Send to you:

Arg function was excluded from Drupal 8. But you can replace it simply.

We have url /node/1

Arg Function in Drupal 7

On Drupal 7 we used it in such way:

echo arg(0); // node
echo arg(1); // 1

Arg Function in Drupal 8

In Drupal 8 we use OOP replacement of this function:

$route_match = Drupal::routeMatch()->getParameter('node');

Drupal::routeMatch()->getParameter('node')

Returns the processed value of the “node” route.

As the result, we have an object, from which we can get not only node id but also fields of a node. For example:

$node_id = $route_match->id(); // We’ve got node id (1)
$node_bundle = $route_match->bundle(); // We’ve got bundle nodes (article).

You may find the following example of function replacement in Drupal 8 on the Internet:

$path_args = explode('/', current_path());
echo $path_args[0]; // node
echo $path_args[1]; // 1

In such case of use, we can catch an error with empty or not existing elements.

That’s why, it’s better to use OOP variant of function replacement, which is suggested by the official drupal.org resource. That’s all. Simply and quickly 🙂 But if you have any difficulties, please, contact us and we’ll save your time and do everything related to Drupal development and customization for you.

3.7/5.0

Article rating (3 Reviews)

Do you find this article useful? Please, let us know your opinion and rate the post!

  • Not bad
  • Good
  • Very Good
  • Great
  • Awesome