Skip to main content

When was the last time your website had a facelift or created a strategy to improve your brand visibility in versatile, exciting, and engaging ways? Revamping your website with interactive content and improved user experience delivers true value to your organization. Website redesigning with a contemporary design, modern trends and enhanced functionality improves your bottom line. 

Why not make invest your time and money in trusted and reliable CMS platform? With a better looking website and navigation experience, drive heavy traffic to your website and easily convert even casual visitors into customers. Even better, when you redesign your website’s content with the most modern content management system like Drupal 8 to take the pain out of your IT problems. 

Drupal is a free, open source software, produced by over a million users in 230 countries speaking 181 languages. Drupal is the best CMS platform for web content management among global enterprises, governments, higher education institutions, and NGOs. Drupal is highly flexible, secure and scalable to serve your technical and business requirements in Drupal 8 development. Drupal 8 offers powerful digital solutions and is backed by one of the world’s most innovative open source communities.

Here are ten important benefits of redesigning your website with Drupal 8 to meet your business goals:

1. Easy Content Authoring

Drupal is built with essential tools for content creation and publishing, like a customizable WYSIWYG editor to meet the unique requirements of authors, publishers and Drupal developers. Drupal offers role-based permissions for managing editorial workflows as well as content.

2. Responsive Design

According to a recent survey, consumers spend five hours on mobile devices every day. Thirty percent of Google searches are now being performed on some sort of mobile device. Drupal leverages responsive design technology to access content on-the-go from various screen sizes and devices such as iPhone, Android, and others.

3. Usability & User Experience

When an UX is developed well in a website, visitors will easily find the information they need without delay and frustration. Even though the quality of content, graphic design, and the reputation of a company is great, a website design that is not logical and orderly leads to a bad user experience.

4. Image Optimization

Images causes some sites to be painfully slow. Drupal 8 websites are amazing with beautiful images optimized for search engines and you can save on data as well.

5. Website Performance 
 
Optimizing the speed of the web pages by minimizing HTTP requests, minifying HTML, CSS and Javascript, caching, deferring parsing of javascripts, avoiding bad requests and using content delivery networks can just ensure a rewarding browsing experience.

6. Data Migration

If you're running into a lot of roadblocks when you try to update your current site, you have to redesign with a new CMS. Drupal 8 allows you to very easily import your database  including critical pages, images, or downloadable files 

7. Website Security

Drupal 8 is built with comprehensive security by default to safeguard website content and manage its accessibility. The important security features and improvements include HTML generation with Twig templates, cross site scripting, SQL injection, use of PHP as input format, improved content entry and filtering, route definitions, clickjacking protection, CSP support, and more

8. PHP 7 Compatibility

Drupal 8 is PHP 7-ready and sites that run many contrib modules, or particularly memory-intensive need increased memory requirements.  Drupal 8 performance optimization with PHP 7 maximizes the overall page speed and performance of the website.  

9. SEO-friendly CMS

Search engine optimization is an integral part of any website. Drupal 8 comes with out-of-the-box built-in SEO features to drive heavy traffic to the website and improve search engine rankings. Drupal 8 is optimized for SEO with increased site speed, responsive web design, mobile-readiness, content-as-a-service capabilities, clean URLs, advanced search, multilingual sitemap and more to increase the reach and visibility of your website.

10. Multilingual Website

Drupal publishes a single web site or shares content in multiple languages across multiple devices. Drupal 8 is configured with complete and powerful translation module with multiple language handling, interface translation, content translation, and configuration translation to deliver better experience than ever before and save incredible amount of time and money.

Drupal 8 is powered with improved features and functionality, and as the platform matures, it is poised to become the backbone of more and more digital experiences.
 

A web service is a software system designed to support interoperable machine-to-machine interaction over a network. Web services is a well-defined way for two computers to communicate with each other over the internet. 

Drupal web services is always a good option for you

In Drupal, web service is being used to communicate with other web applications or mobile applications. Content can be shared and easily integrated with other applications as well. 

Why use web services in Drupal?

Web services are useful because they present us with an architecture where a resource on a site (an image, textual content, such as a node ID or block ID, a video or audio file) is given a unique identifier. 

Use cases 

For example, in Drupal, every node has an ID. Every file you upload to a Drupal site also has a unique path to it.

This is extremely useful since all applications share this common semantic standard. We name things similarly on all of our web applications. 

Drupal services and real world examples

Here are some examples, perhaps we have to build a product site and they are developing a app for that product site in mobile, then we can pass data from web to mobile app using the web service.  For example if the HR Department wants to integrate its job postings and applications with another web application such as job portals, web services can make this happen.

Advantages of Drupal web development services you can’t ignore

This leads to another advantage of using web services with Drupal and why we would choose to use Drupal in the first place. Instead of having to upload our photos twice—once to our Drupal site and then repeating the procedure to our some other applications, services allows us to upload the images to our Drupal site once and then automatically send that data over to other application which wants without having to upload one (or even a batch of images) again. It saves us time and speeds up the entire process of generating web-based content.

Building web services for Drupal 7

Drupal can use web services following any of the protocols mentioned earlier, including XML-RPC, REST, and SOAP. Drupal can consume web services by requesting data from other web applications using RSS and XML-formatted requests. As a Drupal developer, you can write your own service code in Drupal using PHP. You can also use the Services module as well as other service-specific contributed modules to create these web service requests.

Service module supports multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF and more.

Make use of Drupal Services module for:

  • Integration with core Drupal functionality like files, nodes, taxonomy, users, files and more.
  • Response format API allows you to define response Formats for CONTENT-TYPE ie. application/json or application/xml. (also calls such as ENDPOINT/node/1.json work)

Additionally, all the communication between services, in our example between a client and a server, happens over HTTP (the standard web protocol). This is a uniform protocol that is used for transport and communication of the service. All transports take place uniformly using GET, POST, PUT, and DELETE requests, for example.

The HTTP requests are stand alone and occurs at one given moment and is isolated from all other activated requests. If HTTP requests works and gets a response, it succeeds. If HTTP requests doesn’t get response from the server or application it's communicating with, it fails. The requests can be repeated an infinite number of times.
 

Drupal is PHP 7-ready and sites that run many contrib modules, or particularly memory-intensive ones, will need more memory requirements. Optimizing Drupal website performance with PHP 7 version will boost the overall page speed. 

PHP 7 was released in December 2015 and offers high performance, huge load capacity and asynchronous programming support  for online applications. According to the latest study, PHP 7 is twice as fast as PHP 5.6 and reduces memory usage.

PHP 7

Why this is the right time to move to PHP 7

Drupal 7 core officially supports PHP 5.2.5 or higher  However, PHP 7 introduces backward incompatible changes which may need to be addressed in contributed or custom modules and themes. While some Drupal 7 sites may run on minimum of PHP versions, you can move to Drupal 8 with PHP 7 support to enhance the performance of the site.

Drupal 8 officially supports 200+ new features and improved functionalities, and upgrading to PHP 7 brings a lot of improvements and delivers high performance Drupal site, whether you are a website owner or a Drupal developer

Drupal core's automated test suite is now fully passing on a variety of environments where there were previously some failures (PHP 5.4, 5.5, 5.6, and 7). Several bugs affecting those versions were fixed as well. These PHP versions are officially supported by Drupal 7 and recommended for use where possible.

Anecdotal evidence from a variety of users suggests that Drupal 7 can be successfully used on PHP 7, both before and after the 7.50 release. 

A slow website load time impacts visitors, overall user experience, and the bottom line. With the improved speed enhancements of Drupal 7 and Drupal 8 with PHP 7, your user engagement and experience will increase and less likely they will leave your website

A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. The service is made part of the client's state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern." Dependency injection is an advanced software design pattern and applying it will increase flexibility. Once you wrap your head around this pattern, you will be unstoppable.

A practical example of accessing services in objects using dependency injection

For the following example, let's assume we are creating a method that will use the service of A, we need to pull the dependencies of B and C into the plugin which we can use to inject whichever services we require.

  • Application needs A so:
  • Application gets A from the Container, so:
  • Container creates C
  • Container creates B and gives it C
  • Container creates A and gives it B
  • Application calls A
  • A calls B
  • B does something

Types of Dependency Injection

There are different types of Dependency Injection:

  • Constructor injection
  • Method injection
  • Setter and property injection
  • PHP callable injection

Constructor Injection

The DI container supports constructor injection with the help of type hints(Type hinting we can specify the expected data type) for constructor parameters. The type hints tell the container which classes or interfaces are dependent when it is used to create a new object. The container will try to get the instances of the dependent classes or interfaces and then inject them into the new object through the constructor.

Method Injection 

In constructor injection we saw that the dependent class will use the same concrete class for its entire lifetime. Now if we need to pass separate concrete class on each invocation of the method, we have to pass the dependency in the method only.

Setter & Property Injection

Now we have discussed two scenarios where in constructor injection we knew that the dependent class will use one concrete class for the entire lifetime. The second approach is to use the method injection where we can pass the concrete class object in the action method itself. But what if the responsibility of selection of concrete class and invocation of method are in separate places. In such cases we need property injection.

PHP Callable Injection

Container will use a registered PHP callable to build new instances of a class. Each time when yii\di\Container::get() is called, the corresponding callable will be invoked. The callable is responsible to resolve the dependencies and inject them appropriately to the newly created objects

Dependency Injection: Advantages & Disadvantages

Advantages

Reducing the dependency to each other of objects in application.
Unit testing is made easier.
Loosely couple 
Promotes re-usability of code or objects in different applications
Promotes logical abstraction of components.

Disadvantages

DI increases complexity, usually by increasing the number of classes since responsibilities are separated more, which is not always beneficial.
Code will be coupled to the dependency injection framework.
It takes time to learn
If misunderstood it can lead to more harm than good

Summary

Dependency injection is a very simple concept of decoupling your code and easier to read. By injecting dependencies to objects we can isolate their purpose and easily swap them with others. 

The service container is basically there to manage some classes. It keeps track of what a certain service needs before getting instantiated, does it for you and all you have to do is access the container to request that service. Using it the right way will save time and frustration, while Drupal developers will even make it easier for the layman. 

 

Learn about the Drupal community coding standards and best practices that every Drupal developer should care whenever writing the code for Drupal. If you are truly committed to Drupal, then you should guarantee the code you contribute back be standards compliant. Here are ten of the best practices for implementing Drupal coding standards:

1. Spacing and Tabbing

  • Use double space (not tab, yes both are different) for indentation 
  • Often, the IDE/Editor that we use for Drupal development aggravates this issue as most of the IDE is configured to use tab for every line-break.
  • Press <ENTER> ensure that it aligns the cursor to the same indent as previous line with tabbing that caused this indentation issue.

2. Code comments

  • Check this link below for Drupal comment standards (https://www.drupal.org/node/1354). Comments are generally defined and used to state what the following line of code or block of code is doing and why we are writing the logic that way if it needs explanation for any future Drupal developer.
  • Three types of comments can be used in Drupal, Single line commenting (starts with //), Multi-line commenting (starts with /*) and Doxygen commenting (starts with /**).
  • Single line commenting and Doxygen commenting has a wide following in Drupal. Even for the comments with more than a line, it is handled with repeat use of single line commenting. The following example shows the usage pattern:

         // The first line of the comment goes here.
        // Some other comment here.
        // Some more comments here.
        // This saves the $node object and creates/updates the node
           node_save($node);

  • Comments are strictly not to be used to invalidate the code, which means you can’t use the comments to comment-out some set of code that you think are not needed. 
  • If you think some block of code is not really needed, just remove them instead of commenting-it-out. 
  • Sometimes you might find, the block of code that may be needed in future but not needed right now. In such instances, you can invalidate the code by placing those unwanted code in the condition like mentioned below.

         if (0) {
         // Some big logic goes here
        // that are not needed in this release for production
        }

  • The above code gets invalidated, that is will not be executed ever as the condition "if (0)" always returns "FALSE", So the block of code inside that condition will not be executed.

3. Naming the function and variables

  • PHP was just procedural at the time of initial Drupal release. So all the coding standard in Drupal follows as such. That means all the function and variables should follow snake  case structure (as of Drupal7), which means variable names should start with small-letter words and underscore should be used to connect the words if the variable is going to contain multiple words. ($snake_case)
  • With the release of Drupal 8, the naming of variables and functions can also be used using camelCase structure, which means variable names should start with small-letter words with uppercase initials for the connective words in case of multi-word variable. (Eg. $camelCase)
  • In either way, we need to follow only one case throughout the file.
  • What we forget is, we mix cases (camelCase and snake_case) sometimes. This should be avoided. Sometimes we define functions without grouping of the function name. In Drupal, all the functions inside a module should be prefixed with the module name, which is called grouping of the function. This helps in avoiding the name conflicts between modules.

4. Uppercase variables

  • According to Drupal coding standard, UPPERCASE variables are considered as constants whether it's PHP constants (TRUE, FALSE, NULL) or Drupal constants (Eg: LANGUAGE_NONE).
  • Sometimes in order to stress the importance of variables, we name the variables in uppercase. This should be avoided.

5. Operator and logical statements

  •  We often forget to leave a space before and after the usage of operator (Eg. if(arg(0)=='node')). According to the Drupal coding standards, all the operators should have single space before and after the operator (Eg. if (arg(0) == 'node')).
  •  Use single space before the start curly braces. The opening curly should be on the same line as the opening statement, guided by single space. The closing curly brace should be on the end of the block and indented to the same level as the opening statement.

6. Line length and Wrapping

  • In general, all lines of code should be no longer than 80 characters. However, there are exceptions to the character limit for the variable and function name that are quite longer when correctly indented.
  • We often wrap the condition of the control statement for readability. Drupal coding standard encourages us to split the multiple conditions and evaluate each complex conditions into a variable and use that in the control statement for better readability.

7. Module placement

As far as Drupal 7 is considered, all the contributed modules should be grouped under the directory called "contrib" in "/sites/all/modules", whereas the custom modules should go inside "/sites/all/modules/custom". In Drupal 8, the same can be followed or utilize the "/module" directory and use the same grouping of the  modules.

8. Writing Javascript

  • Always use Drupal behavior for your custom scripts which runs every time there is change in DOM elements unlike the traditional jQuery.ready which runs only once during the page execution when the DOM elements are ready.

9. Placeholders for translate function t()

  • Use the placeholders for dynamic strings used inside t() function.
  • Generally t() function is used to translate the given strings, sometimes we might use the dynamic strings inside t() function by concatenating the values, which is the not the best practice formulated by Drupal.

     Example:

  • return t('@username, welcome to my website', array('@username' => $account->name));

10. Module file

  • Use the module file only for Drupal hooks and some commonly used custom functions that you need frequently. 
  • Use .inc file to define menu callbacks and other helper functions that are not needed to be defined in module file.

If we all code to standards, Drupal will be a stronger, more performant, more secure platform. Drupal will continue to grow and strengthen it’s community due to the quality of it’s codebase. Anubavam has been building Drupal sites and providing services such as Drupal 8 upgrade and migration services, Drupal E-commerce development services, and more. Anubavam is participating in Drupal core development since 2006 and has delivered 250+ projects to 100+ happy clients in 22 countries worldwide.

In Drupal 8, there is a need to store information associated with a user's session. There are two services for temporarily storing user-specific and non-user-specific data in key/value format, namely, use user.private_tempstore and user.shared_tempstore.

TempStore

A tempstore is for data that needs to be persisted between requests without being saved back to the canonical storage (such as an entity or configuration object).  

Two methods can be effectively used for  private_tempstore - Use "\Drupal::service()" and Dependency Injection.

Use "\Drupal::service()"

To set Temporary Data

$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('my_variable_name', $some_data);

To read Temporary Data

$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->get('my_variable_name', $some_data);

PrivateTempStore

A PrivateTempStore can be used to make temporary, non-cache data available across requests. The data for the PrivateTempStore is stored in one key/value collection. PrivateTempStore data expires automatically after a given timeframe.

Dependency Injection

  • To use this service need to invoke the following “use” statement

          use Drupal\user\PrivateTempStoreFactory;

          use Symfony\Component\DependencyInjection\ContainerInterface;

  • Temporary store - that is private to the current user.

Storing session data vs storing temporary data

Which is efficient, storing data using session variable or use data for a limited term. Let's see which approach is preferable: 

  • Both are used for same purpose.
  • But Drupal 8 services provides needed abstraction and structure for interacting with a global construct. It's part of an overall architecture that allows Drupal developers to build and extend complex applications.
  • Use session manager for anonymous user to store the data.

Stay connected with the latest news on web strategy, design, and Drupal 8 development.
 

Site speed is crucial when you run a site. If a site takes too much time to load, visitors will get frustrated and leave the site to go elsewhere. Slower performing sites don't rank well on search engines.
 
Drupal performance optimization can be a complicated specialization in its own right. It takes too long to investigate performance issues and fix them. However, here are some quick fixes and simple methods to move you into the right direction. 
 
1. Keep the core, contrib module and themes updated
 
It is critical that you are running the most recent Drupal version as updates by and large contain bug fixes and performance improvements. Keep the core, contribs module, and themes with the latest Drupal update.
 
To run updates, navigate to “Reports” → “Available Updates.”
You can then click on “Check manually” to scan for additional updates.
 
     
2. Enable Page Caching  
 
To enable, navigate to “Configuration” → “Development” → “Performance.”
Enable “Cache pages for anonymous users” and also “Cache blocks.” You can then choose a time value for minimum cache lifetime and expiration of cached pages.
Click on “Save configuration.”
 
3. Turn on Block Caching 
 
Enable caching options for all the blocks that will boost the performance.
 
4. Aggregate Javascript and CSS files  
 
Browser doesn’t have to fetch as many files and it reduces the total number of HTTP requests being made. Enhance your frontend performance and download times by aggregating your CSS and Javascript files.
 
To enable, navigate to “Configuration” → “Development” → “Performance.”
Enable “Aggregate and compress CSS files” and “Aggregate Javascript files.”
Click on “Save configuration.”
 
5. Disable unnecessary modules
 
Every module adds to the amount of code that needs to be available for a page load. And it also increases the number of lookups. Wherever possible use a generic module in place of multiple module that does specific functionalities.
 
6. Cache views content
 
The views module is probably one of the most popular modules on Drupal 8 development. If you have it installed you can also enable caching on it.
 
To enable, navigate to “Administration” → “Structure” → “Views.”
Click “Edit” on the view you want to enable caching on.
Expand the “Advanced box.”
Select “Time-based” and click on “Apply (all displays).”
 
7. Disable DB logging 
 
When the Database Logging module is enabled, you're shown with a menu item in the "Logging and alerts" of the site configuration. When the Database Logging module is disabled, although the menu item for Database logging goes away, "Logging and Alerts" becomes empty and stays there. If you visit admin/settings/logging, you're shown with an empty page.
 
8. Reduce 404 Errors
 
Use third party services such as “online Broken Link Checker” or a tool like Screaming Frog and avoid using a module to check for 404s and save your server’s resources.
 
Stay away from expensive 404 errors using Drupal Fast 404 module as it can normally such errors with less than 1MB of memory.
 
9. Fast 404 Responses 
 
When your site has broken images or CSS file paths, it will reduce the page speed significantly The Fast 404 module changes the way 404 errors are handled, delivering fast 404 error messages.
 
10. Compress Images 
 
The loading speed of large image files are slow. Make the file size smaller so they are not larger than they need to be. For image fields, you can use image styles (admin/config/media/image-styles) to resize images to the desired size.
 
11. Use Sprite Sheets
 
An image sprite is an aggregation of a single image. A web page loaded with a number of images is slow to load and generates multiple server requests. Reduce multiple server requests with image sprites and save bandwidth.
 
12. Lazy Loading of Images 
 
Lazy loading images can substantially increase your page load times by ensuring the image will only load when it is visible to the browser window. “Image Lazyloader” is the most popular Drupal module over 18,000 downloads.
 
13. Content Delivery Network
 
Implementing a Content Delivery Network (CDN) with Drupal is a fast and easy way to instantly see decreased load times for your website. Protect your digital assets such as product images, javascript, CSS across the world will ensure that they are delivered faster to your visitors and reducing latency.
 
This represents a run down of 13 easier ways to boost the performance of Drupal sites. Track the changes to ensure that there is actually an improvement in the performance.
 
Let me know in the comments below if you can think of any more quick wins to improve performance of a Drupal site.
 
 

Drupal 8 Form API is similar to Drupal 7 form API. The forms are still represented with nested array structure as Drupal 7 to render the data. However, there is a separate validation and submission form as well.

Form Generation

  • There are different classes, functions and interfaces to choose depending on the type of form you are creating.
  • Drupal 8 has some new HTML 5 elements (telephone, email, date) to render array structure.
  • The basic workflow of a form is defined by buildForm, validateForm, and submitForm methods of the interface.
     

Create a Directory Structure

Create a directory within a new custom module. 

Example 

Create your formExample.module in below directory structure

modules/formExample/
css
js
src
    Controller
         formExampleController.php
    Form
         formExampleForm.php
    Entity
          tomato.php
formExample.info.yml
formExample.routing.yml
formExample.module

Form ID

This needs to return a string that is the unique ID of your form. Namespace the form ID based on your module's name.

Example

Drupal 8

public function getFormId() {
       return 'multistep_form_one';
}

Drupal 7

function multistep_form_one($form,$form_state) {

}

buildForm

This needs to returns a Form API array that defines each of the elements your form is composed of.

Example

public function bulidForm(array $form, FormStateInterface $form_state) {
       $form[‘name’] = array(
            ‘#type’ => ‘textfield’,
            ‘title’=> ‘name’,
       );
       return $form;
}

validateForm

Example

public function validateForm(array $form, FormStateInterface $form_state) {
       if(!is_numeric($form_state->getValue(‘name’)){
           $form_state->setErrorByName(“Enter only alphabets”);
       }
}

submitForm

Example

public function submitForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state->getValues() as $key => $value) {
      drupal_set_message($key . ': ' . $value);
    }
}

 

We are done with creating custom form elements, fields, field formatters, etc. in Drupal 8. Our expert Drupal developers will be covering session data storage with Drupal 8 in future posts in this series. Join the conversation by commenting below with any questions or feedback on using these Drupal 8 constructs.

With Drupal 8, significant changes has been brought for developers: new features and backwards-compatible changes, new APIs, deprecated modules, and more. One of the biggest changes is Drupal 8's unified database query API that fundamentally alters the way most Drupal developers will build database queries in Drupal.

The following database types are supported in Drupal 7 & Drupal 8:

Drupal 7

  • MySQL, MariaDB, or equivalent
  • PostgreSQL
  • SQLite

Drupal 8

  • MySQL, MariaDB, Percona Server, or equivalent
  • PostgreSQL
  • SQLite

Database abstraction layer - One query for all type of database

Allow the use of different database servers using the same code base.
Drupal provides a database abstraction layer to provide developers with the ability to support multiple database servers easily. 

The intent of this layer is to preserve the syntax and power of SQL as much as possible, but also allow developers a way to leverage more complex functionality in a unified way. 

It also provides a structured interface for dynamically constructing queries when appropriate, and enforcing security checks and similar good practices.

It’s PHP’s PDO (recursive acronym of PHP Data Object. Definition: The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP).

Drupal query

Query Types:

  • Static Query
  • Dynamic Query

Static and Dynamic queries

Static queries 

The most common form of query in Drupal is a static query. Only very simple queries should use the static query mechanism.
db_query

Dynamic queries

Dynamic queries refer to queries that are built dynamically by Drupal rather than provided as an explicit query string. All Insert, Update, Delete, and Merge queries must be dynamic.
db_select, db_insert, db_delete, db_update, db_merge

D7 db_query 

Executes an arbitrary query string against the active database.

db_query($query, array $args = array(), array $options = array())

// Fetch the results from node table where the node belongs to specified ids

Example

db_query("SELECT * FROM {node} WHERE nid IN (13, 42, 144)");

Using placeholders  (:placeholder_name)

db_query("SELECT * FROM {node} WHERE nid IN (:nids)", array(':nids' => array(13, 42, 144));
or
$nids = array(13, 42, 144);
db_query("SELECT * FROM {node} WHERE nid IN (:nids)", array(':nids' => $nids);

Note: Curly braces ( { } ) are not mandatory in either case

D8 db_query

Executes an arbitrary query string against the active database.

db_query($query, array $args = array(), array $options = array())

Note: Drupal8 discourages us to use db_query as it is marked as deprecated in Drupal8 and will be definitely removed from Drupal 9.

D7 db_select
Returns a new SelectQuery object for the active database.

db_select($table, $alias = NULL, array $options = array())  

// Fetch the results from node table where the node belongs to specified ids

Example

$result = db_select(node, 'n')
    ->fields('n')
    ->execute()
    ->fetchAssoc();

Select particular column 

$result = db_select(node, 'n')
    ->fields('n', array('nid', 'title'))
    ->execute()
    ->fetchAssoc();

Note: Curly braces ( { } ) are not mandatory in either case

D8 db_select
Returns a new SelectQuery object for the active database.

db_select($table, $alias = NULL, array $options = []) 

Tips: [] is supported since PHP version 5.4, it can be used instead of specifying array().

Example

$db = \Drupal::database();
$result = $db->select('node', 'n');
    $query->fields('n');
    $query->condition('type', "page", "=");
    $result = $query->execute()->fetchAll();
     print_r($result);

D7 db_insert
Returns a new InsertQuery object for the active database.

db_insert($table, array $options = array()) 

Example

$nid = db_insert('node')
->fields(array(
  'title' => 'Example',
  'uid' => 1,
  'created' => REQUEST_TIME,
))
->execute();

/** similar to **/

$result = db_query("INSERT INTO {node} (title, uid, created) VALUES (%s, %d, %d)", 'Example', 1, time());

D8 db_insert
Returns a new InsertQuery object for the active database.

db_insert($table, array $options = array()) 

Example

$conn = Database::getConnection();
$conn->insert('contact_form')->fields(
  array(
    'sender_name' => $name,
    'sender_email' => $email,
    'sender_subject' => $recipient,
    'sender_message' => $message,
  )
)->execute();

D7 db_update
Returns a new UpdateQuery object for the active database.

db_update($table, array $options = array()) 

Example

$num_updated = db_update('node')
  ->fields(array(
    'status' => 1,
  ))
  ->condition('uid', 5, '=')
  ->execute(); 

// Above Example is Equivalent to the following:

$result = db_query("UPDATE {node} SET status = %d WHERE uid = %d", 1, 5);

D8 db_update
Returns a new UpdateQuery object for the active database.

db_update($table, array $options = array())

 Example

$query = \Drupal::database()->update('file_managed');
$query->fields([
'uri' =>$uri,
]);
$query->condition('fid', $fid, ‘=’);
$query->execute();

D7 db_delete

Returns a new DeleteQuery object for the active database.

db_delete($table, array $options = array())

Example

$num_deleted = db_delete('node')
  ->condition('uid', 5)
  ->execute();

equivalent to →DELETE FROM {node} WHERE uid=5;

D8 db_delete
Returns a new DeleteQuery object for the active database.

db_delete($table, array $options = []) 

Example

db_delete('block')
    ->condition('module', 'menu')
    ->condition('delta', $delta, ‘=’)
    ->execute();

D7 and D8 db_merge
Returns a new MergeQuery object for the active database.

db_merge($table, array $options = array()) 

Example

db_merge('example')
  ->key(array('name' => $name))
  ->fields(array(
      'field1' => $value1,
      'field2' => $value2,
  ))
  ->execute();

db_truncate
Returns a new TruncateQuery object for the active database.

db_truncate($table, array $options = []) 

Example

db_truncate('mytable')
->execute();

Both D7 and D8 shares the same syntax, but in D8 its mentioned as deprecated and advised to use dependency injection for such operations.

db_set_active
Sets a new active database.

db_set_active($key = ‘default’) 

Example

db_set_active('yourdatabasekey');

Note: Deprecated as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Use \Drupal\Core\Database\Database::setActiveConnection() instead.

EntityFieldQuery
Retrieves entities matching a given set of conditions.

  • When building complex web applications, you’ll eventually have to interact with a database. 
  • To retrieve data in Drupal one can use the database abstraction layer provided, which requires some SQL knowledge to be used properly. 
  • When Drupal 7 EntityFieldQuery API is provided, it lets you fetch information about entities from Drupal without actually building SQL queries. 


D7 example

$taxonomnyQuery = new EntityFieldQuery();
  $terms = $taxonomnyQuery->entityCondition('entity_type', 'taxonomy_term')
    ->propertyCondition('vid', 2)
    ->fieldCondition('field_status', 'value', 1)
    ->propertyOrderBy('tid', 'DESC')
    ->range(0, 5)
    ->execute();

Entity API

Describes how to define and manipulate content and configuration entities.

D8

$cids = \Drupal::entityQuery('comment')

    ->condition('entity_id', $nodeID)
    ->condition('entity_type', 'node')
    ->sort('cid', 'DESC')
    ->execute();

Another example, using the core File entity:

 

$fids = Drupal::entityQuery('file')
  ->condition('status', FILE_STATUS_PERMANENT, '<>')
  ->condition('changed', REQUEST_TIME - $age, '<')
  ->range(0, 100)
  ->execute();

 

Hooks are PHP functions that are created for each module when system events happen, e.g. page load or user login.
In Drupal 7 custom pages are created using hook_menu. Drupal 8 is yaml-based and you need create controller, routes.yml and basic info file for your module.

Comparison of hooks in Drupal 7 & Drupal 8 

  • Number of hooks in Drupal 7:  352
  • Number of hooks in Drupal 8:  338
  • Deprecated hooks: 83 
  • New hooks in Drupal 8: 56
  • Renamed hooks: at least 4

Examples of deprecated hooks

Hook_Menu

 hook_menu() -> Drupal 8 APIs should start with defining the routes for the items.    

<?php
    # Drupal 7 menu item
    $items['admin/content/book'] = array(
    'title' => 'Books',
    'description' => "Manage your site's book outlines.",
    'page callback' => 'book_admin_overview',
    'access arguments' => array('administer book outlines'),
    'type' => MENU_LOCAL_TASK,
    'file' => 'book.admin.inc',
  );
?>

 

# Drupal 8 book.routing.yml snippet
book.admin:
  path: '/admin/content/book'
defaults:
    _controller: ‘\Drupalbook\Controller\BookController::adminOverview'
    _title: 'Books'
requirements:
    _permission: 'administer book outlines‘
     # Drupal 8 book.links.task.yml snippet
book.admin:
  route_name: book.admin
  title: 'Books'
  base_route: system.admin_content

hook_init() -> Drupal 8 has adopted symfony as a part of its core. It uses Symfony kernel and events to do the same now.

<?php
function mymodule_init() {
  if (!empty($_GET['redirect-me'])) {
     drupal_goto('http://example.com/');
  }
}
?>

If your module just needs to add css and/or javascript, hook_page_attachments should be used in.

function MYMODULE_page_attachments(array &$attachments) { 
  $attachments ['#attached']['library'][] = 'modulename/libraryname'; 
}

Hook_Block

hook_block_configure , hook_block_info, hook_block_view -> A "plugin" is just a new way of creating reusable elements in Drupal. Blocks are now created with plugins. 
modules/yourmodule/src/Plugin/Block/YourBlockName.php

<?php
/**
 * Provides a 'Hello' Block
 *
 * @Block(
 *   id = "hello_block",
 *   admin_label = @Translation("Hello block"),
 * )
 */

namespace Drupal\hello_world\Plugin\Block;
use Drupal\Core\Block\BlockBase;
class HelloBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#markup' => $this->t('Hello, World!'),
    );
  }
}
?>

Creating a hook

As a Drupal Developer the easiest way to implement a hook is to copy the example from the .api.php file into your module, then rename the function by replacing the starting 'HOOK' with the name of your module. For example, if your module is named 'mymodule' and you're using a form_alter, hook_form_alter becomes mymodule_form_alter.

Then write the desired functionality, returning output how the hook requires. Hook return values might be set in passed parameters rather than a return statement in the function.
 

Subscribe to Drupal Application Development
 

start with anubavam today

You have an idea we have engineers to convert your ideas into reality

Request Quote