Drupal 8 Frequently Used Services, Functions, and Statements

17 / Jul / 2017 by Jeet Lal 3 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?

[php]
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);
[/php]

Sometimes we need a relative path and sometimes we need an absolute path. Drupal 8 has options parameters 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?

[php]
$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];}
[/php]

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

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

[php]
{{ kint() }}
[/php]

4. How to get the current Path in Drupal 8?

[php]
$currentPath = \Drupal::service(‘path.current’)->getPath();
[/php]

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?

[php]
$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));
[/php]

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

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

[php]
$moduleHandler = \Drupal::service(‘module_handler’);
if ($moduleHandler->moduleExists(‘module_name’)){
//echo “module installed”;} else {//echo “module does not installed”;}
[/php]

7. How to get Route name in Drupal 8?

[php]
$route = \Drupal::routeMatch()->getRouteName();
[/php]

The above statement will return the Drupal route. It returns an 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 the current page title in Drupal 8?

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

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

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

[php]
$image_path = \Drupal::service(‘file_system’)->realpath();
[/php]

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

10. How to check the Frontpage in Drupal 8?

[php]
$is_front = \Drupal::service(‘path.matcher’)->isFrontPage();
[/php]

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

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

[php]
\Drupal::service(‘page_cache_kill_switch’)->trigger();
[/php]

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 the Drupal cache.

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

[php]
$response = new \Drupal\Core\Routing\TrustedRedirectResponse($absolute_url, 300);
;”>$response->send();
exit(0);
[/php]

The above statement will redirect on the third-party website with Redirect permanent status. The URL must have an 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 (3)

Leave a Reply

Your email address will not be published. Required fields are marked *