7

How do I get arguments from the URL? in other words, what is the equivalent of the arg() function of Drupal 7 and previous versions?

1
  • I'm the maintainer for the D7 Ported Functions for D8/9 module, which seeks to port Drupal 7 functions into drupal 8/9 to make development easier. We have an arg() drop-in replacement for Drupal 8/9. It's d7d8_arg().
    – Richard
    Jun 2, 2020 at 1:48

2 Answers 2

16

As reported in the arg() is deprecated and will be removed change record, the Drupal 8 (procedural) equivalent of arg() is the following one.

$current_path = \Drupal::service('path.current')->getPath();
$path_args = explode('/', $current_path);

As the change record makes notice, not all the times that is the correct code to use. Depending from the context, you should use code similar to the following one.

  • Check if a path is for an administrative page

    if (\Drupal::service('router.admin_context')->isAdminRoute()) {
      // Your code.
    }
    
  • Add CSS or JavaScript conditionally, basing on the page being visited

    function mymodule_page_attachments(array &$attachments) {
      if (\Drupal::routeMatch()->getRouteName() == 'my.route') {
        $attachments ['#attached']['library'][] = 'my_module/my_library'; // you'll need to define in mymodule.libraries.yml
      }
    }
    
  • Load the currently viewed node

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

Notice that in the first and last case, in Drupal 7 you should not use arg(), but respectively path_is_admin() and menu_get_object(). The typical beginner-Drupal-developer error is using arg() also in those cases.

4

arg() is deprecated in drupal 8, however we can get values like arg() function does in drupal 7 & 6 by mentioned

$path = \Drupal::request()->getpathInfo();
$arg  = explode('/',$path);
print_r($arg); exit(); 

The output would be parameters in url except basepath or (baseurl),

Array
(
   [0] => 
   [1] => node
   [2] => add
)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.