Drupal 8 Frequently Used Services, Functions, and Statements

17 / Jul / 2017 by Jeet Lal 1 comments

In Drupal 8, some important services, functions and statements are frequently used in all projects. These are time-saving statements and perform a very crucial operation. Drupal 8 have multiple statements that are very useful in the project and it is also essential for the performance & Drupal 8 standard.

Drupal 8 follow a PSR-4 standard, so Drupal 8 recommended the use of the PSR-4 standard code for the better performance. Drupal 8 provides a lot of services, statements & functions that are very prominent for a big project where performance is the priority. We need these statements very frequently in Drupal 8 projects and we start searching on Google, which is a very time-consuming task and sometimes it is not possible when you are working offline.

In Drupal 8 project, these statements/services play very a vital role in performance, stability, and reusability because these are short line code and increases code reusability.

In Drupal 8, a service is any object managed by the services container.
Drupal 8 introduces a new concept of services to decouple reusability and makes these services pluggable and replaceable by registering them with a service container. It’s a best practice to use these services provided by Drupal 8. The Symfony 2 documentation has a wide introduction to services.

Following are frequently used statements, services and functions:

1. Drupal 8, How to get Node alias or Taxonomy Alias by Node id or Term ID?

</span>
use Drupal\Core\Url;

$options = array('absolute' => true);
//return node alias
$url = Url::fromRoute('entity.node.canonical', ['node' => 1234], $options);

//return taxonomy alias
$url = Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => 1234], $options);

Sometimes we need a relative path and sometimes we need an absolute path. Drupal 8 has options parameter where you can pass true or false in an absolute key.

Parameters description:
-absolute true will return absolute path.
-absolute false will return relative path.

2. Drupal 8, How to get Node ID or Taxonomy term ID by Drupal alias or path?

$path = \Drupal::service('path.alias_manager')->getPathByAlias('/alias-path');
if(preg_match('/node\/(\d+)/', $path, $matches))
	$nodeID = $matches[1];

$path = \Drupal::service('path.alias_manager')->getPathByAlias('/alias-path');
if(preg_match('/taxonomy\/term\/(\d+)/', $path, $matches)) {$termID = $matches[1];}

$path = \Drupal::service('path.alias_manager')->getPathByAlias('/alias-path');
if(preg_match('/user\/(\d+)/', $path, $matches)) {$userID = $matches[1];}

If alias-path does not exist, it will return the same argumented string.
The first example will work for the node, second for the taxonomy and third for the users.

3. Drupal 8, How to get the object in twig file?
If you are looking to print how many objects have passed into twig file, simply add a line in your .twig file.

{{ kint() }}

4. How to get current Path in Drupal 8?

$currentPath  = \Drupal::service('path.current')->getPath();

It will return the current path in Drupal 8. For the node pages it return node/{node id},for taxonomy taxonomy/term/{term id}, for user user/{user id) if exists otherwise it will return the current request URI.

5. How to get Affected rows by Delete or Update statement in Drupal 8?

$query        = "Delete FROM table_name where id=10 ";
$affectedRows = $this->database->query($query,[],array('return' => Database::RETURN_AFFECTED));

$query        = "Update table_name set couln_name=value where id=10 ";
$affectedRows = $this->database->query($query,[],array('return' => Database::RETURN_AFFECTED));

The above statements will return the number of rows affected by SQL statement.

6. How to check whether a module is installed or not in Drupal 8?

$moduleHandler = \Drupal::service('module_handler');
if ($moduleHandler->moduleExists('module_name')){
//echo  "module installed";} else {//echo  "module does not installed";}

7. How to get Route name in Drupal 8?

$route = \Drupal::routeMatch()->getRouteName();

The above statement will return Drupal route. It returns entity.node.canonical for the nodes, system.404 for the 404 pages, entity.taxonomy_term.canonical for the taxonomy pages, entity.user.canonical for the users and custom route name that we define in modulename.routing.yml file.

8. How to get current page title in Drupal 8?

$request = \Drupal::request();
  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
$title = \Drupal::service('title_resolver')->getTitle($request, $route);}

The above statement will return current page title. If you use above statement in the controller, it will also return page title.

9. How to get current Document root path in Drupal 8?

$image_path = \Drupal::service('file_system')->realpath();

The above statement will return the current document root path like /var/www/html/project1.

10. How to check the Front page in Drupal 8?

$is_front = \Drupal::service('path.matcher')->isFrontPage();

The above statement will return either true or false. Return True for the Front page otherwise false.

11. How to uncache a particular page in Drupal 8?

\Drupal::service('page_cache_kill_switch')->trigger();

The above statement doesn’t keep the page in cache. You can use this statement in node_preprocess, controller, etc. with the condition. When this line is executed, the page will not go into Drupal cache.

12. How to redirect third party URL in Drupal 8?

$response = new \Drupal\Core\Routing\TrustedRedirectResponse($absolute_url, 300);
;">$response->send();
exit(0);

The above statement will redirect on the third party website with Redirect permanent status. The URL must have absolute path like http://www.tothenew.com

All the above statements are helpful in Drupal 8, so you should bookmark this blog page to speed-up the project development, maintain the Drupal 8 standard and performance that is the key requirement for any Drupal website.

FOUND THIS USEFUL? SHARE IT

comments (1 “Drupal 8 Frequently Used Services, Functions, and Statements”)

Leave a comment -