By ParisLiakos on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.x
Issue links:
Description:
arg() was deprecated in D8 because it did not serve any specific need.
Most places that had request dependent logic were using an already injected request, instead of the global arg() function.
D7
// Retrieve an array which contains the path pieces.
$path_args = arg();
// Check if the current page is admin.
if (arg(0) == 'admin') {
// This is wrong even in D7. path_is_admin() should be used instead.
}
// Conditionally add css or js in certain page.
function mymodule_page_build(&$page) {
if (arg(0) == 'sth' && arg(1) == 'else') {
drupal_add_css(drupal_get_path('module', 'mymodule') . '/css/my.css');
}
}
// Load the current node.
if (arg(0) == 'node' && is_numeric(arg(1))) {
// This is wrong even in D7. menu_get_object() should be used instead.
}
D8 (procedural)
// Retrieve an array which contains the path pieces.
$current_path = \Drupal::service('path.current')->getPath();
$path_args = explode('/', $current_path);
// Check if the current page is admin.
if (\Drupal::service('router.admin_context')->isAdminRoute(\Drupal::routeMatch()->getRouteObject())) {
}
// Conditionally add css or js in certain page.
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 current node.
$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
}
D8 (OOP)
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Routing\AdminContext;
use Drupal\Core\Routing\RouteMatchInterface;
class myClass {
public function __construct(Request $request, AdminContext $admin_context, RouteMatchInterface $route_match) {
$this->request = $request;
$this->adminContext = $admin_context;
$this->routeMatch = $route_match;
}
public function test() {
// This might change in https://drupal.org/node/2239009
$current_path = $this->request->attributes->get('_system_path');
// Retrieve an array which contains the path pieces.
$path_args = explode('/', $current_path);
// Check if the current page is admin.
if ($this->adminContext->isAdminRoute($this->routeMatch->getRouteObject())) {
}
// Load the current node.
$node = $this->routeMatch->getParameter('node');
if ($node) {
}
}
}
In any case if you still have procedural code that is still dependent on URL paths, you should at least refactor it to check routes and route names instead.
Impacts:
Module developers
Comments
Getting arg in drupal 8
$arg will have numeric array of values;