Arg Function: How to Replace It in Drupal 8

Arg(0 function in Drupal 8

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.

Do you have a question?

Or do you want to talk and share some news? We’ll be glad to communicate with you and clarify all you need. Feel free to contact us anytime, and we’ll reply as soon as possible. Let’s get acquainted and be partners. We’ll be happy to keep in touch with you.

We accept: DOCX, DOC, ODT, PDF

* - required fields