Skip to main content

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 a comprehensive content management framework which offers a number of modules to extend its functionalities with day-to-day updates. If you want to know about ‘Drupal Maintenance’, then you need to know the following things: 

Security updates

  • Upgrade from Drupal 6 to Drupal 7 or Drupal 8
  • Migration from legacy system

Security updates

                   Updating refers to taking your site from one 'minor' version to another minor version. Lets consider an example if a site is in Drupal 7 version D7.1 and latest version is released as D7.2 or from Drupal 8 version D8.1.0 to D8.1.3 then its an update.

Version Upgrades

                 Upgrading refers to taking your site from one 'Major' version to another major version.Switching from Drupal 6 to Drupal 7, or from Drupal 6 to Drupal 8, or from Drupal 7 to Drupal 8 is an 'upgrade'.

Drupal Migration

               You may want to 'migrate' your site from running locally on your computer to an online webhost. Or you may want to 'migrate' your site from one webhost to another. If that is what you want, head to: Backing up and migrating a site.


Steps to Drupal 7 upgrade 

  • Log-in as an user with administrator privileges who can perform "Administer software updates".
  • Turn your site into maintenance mode. Ie. If we are updating a live/production site then go to Administration > Configuration > Development > Maintenance mode. Enable the "Put site into maintenance mode" checkbox and save the configuration.
  • Backup your files and database. Clear the performance cache and delete all the watchdog logs, if any, before taking the database backup.
  • Remove all old core files and directories, except for the 'sites' directory, the original install profile in the 'profiles' directory and any custom files (like htaccess, gitignore or other files) you added elsewhere.
  • To be more specific, in your Drupal root directory, delete all files and the following directories: includes, misc, modules, scripts, and themes. If you made a normal installation, then also delete the profiles folder, but if you used a custom profile, then in the profiles folder, delete the subfolders minimal, standard, and testing.
  • Modifications to the files like .htaccess or robots.txt, needs to be applied from your backup, after the new files are kept in place.
  • Read the release announcement carefully before proceeding the upgrade as the updates may also include changes in settings.php. If you have to use the new settings.php file, then replace the settings.php with the default.settings.php, and apply the site-specific entries like database name, user, and password from the backup file.
  • Any custom files and directories outside the sites directories has to be placed manually. However, it is recommended not to have any custom files or directories outside the sites directory.
  • Download the latest Drupal 7.x core release from http://drupal.org/project/drupal to a directory outside of your web root. Extract the archive and copy the files into your Drupal directory.
  • After copying the new core files, run update url by visiting http://YOURSITENAME/update.php. This will update the core database tables if any alteration to the database table structures is there.
  • In order to access the update.php file please login as administrator. Before you start doing the upgrade process, we have logged in as admin user, get access to the update.php file automatically. In case you had logged out or closed the browser by mistake, you can do the following to access the update.php file.

           Open settings.php with a text editor.
           Look for $update_free_access variable.
           $update_free_access = FALSE;
           Change the access to true:
           $update_free_access = TRUE;
           Now run update.php.
           

  • Once the update is completed, check for errors if any. $update_free_access must be changed back to FALSE for security reasons.
  • Clear the sites performance cache after the upgrade. You can do it by navigating to Configuration => Development => Performance and "Clear all Cache".
  • Check for the status report and report log to verify that everything is working as expected.
  • Once you are error free, make the site online to change the "Put site into maintenance mode" checkbox and save the configuration.


Tips for Drupal site maintenance

  • Keep the Drupal core up-to-date
  • Keep the contributed Drupal modules up-to-date. 
  • Check for the security updates. Install update manager to know the latest available and recommended releases for Drupal core and its contributed modules
  • Configure cron scheduler so that periodic site maintenance will take care of regular checkup and updates
  • Keep the admin user password secure
  • Ensure using check_plain method while assigning or computing values from form post fields to avoid cross-site scripting
  • Write protect the setting.php file.

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.
 

Drupal is powered by best-of-the-breed technologies which makes Drupal highly customizable and scalable. Drupal is free and open source and supported by an active community of over 1.3 million members from 100,000+ contributing users resulting in more than 37,000+ free plug-in and modules as well as themes which extends its core capabilities. 

Drupal 8 provides built-in security by default and simply bug-free modules aren’t enough to address the security challenges. When your site comes under fire from hackers and spambots, you always need an extra layer of security modules that provide your website better protection against exploitable vulnerabilities.

To that end, we have compiled top rated six essential Drupal modules to better protect your website from security vulnerabilities and other risky elements. This will create a strong security layer around your website, and help Drupal developer keep all sorts of Drupal security issues at bay.

1. Password Policy

The Password Policy module is configured with pre-defined parameters for creating secure passwords after ensuring that certain conditions are validated. With a little quick and easy setting of constraints, this security module can keep that door bolted shut from vulnerabilities.

2. TwoFactor Authentification

This module is increasingly used by site administrators to provide an extra layer of security for accessing your Drupal website by using two-factor authentication with onetime password/PINs delivered on your mobile devices. When the pre-generated codes are successfully entered, access is granted to users. This mechanism protects the user account from attackers.

3. Automated Logouts

This module enables site administrators to create a policy of logging out users after a specified period of inactivity. It is highly customizable by role-based permissions to enforce different timeouts. It can be Automated Logout can be easily integrated with Javascript timers.

4. Security Review

This module performs automated testing for security vulnerabilities against traditional attackers. It does not actually make your site secure and locked down, but runs a series of security checks for arbitrary PHP execution, protection against XSS and a lot more, and provides solutions to fix issues.

5. Username Enumeration Prevention

Attackers can easily find usernames with loopholes in the system to access the Drupal site with username enumeration. Attackers can enter a username that does not exist or use the ‘forgot password form’ to get a confirmation message stating that the auth credentials are invalid. When the attacker persists by trying entering random usernames until the valid username has been found. This module will will make it impossible for the attacker to access the Drupal website. When this module is enabled, the error message will be replaced for the standard unknown username and the user will be redirected back to the login form. If the user does not exist, no password reset email will be sent. The attacker
Can no more exploit the username.

6. Security Kit

This module is reliable, user-friendly and provides Drupal with various security hardening options that can be used in your Drupal site to protect against different web application vulnerabilities. This module promises security for cross-site scripting, cross-site request forgery, clickjacking, and SSL/TLS.

Use these six Drupal modules to get maximum protection to your website from unwanted hackers and attackers. Keep your Drupal site safe and secure with all these modules, we would also recommend you to ensure the perfect dose of Drupal development needs with Anubavam.

Drupal 8 is one of the most widely used Content Management System to publish content easily. Drupal  is an open source website development platform. Drupal 8 is used to build websites, from easy to complex, that fits your budget and skill level. Symfony is an open source MVC framework for PHP that powers a lot of websites and it plays a major role with the launch of Drupal 8. Here are some important merits of using Drupal 8.

MERITS

  • Responsive design

Drupal 8 comes with more robust new configuration management system and is compatible with mobile devices and thus it overcomes the limitations of Drupal 7 with regard to mobile devices.

  • Improved semantics with HTML5

Drupal 8 pages are HTML5-based and thus each output template has simplified elements and classes with native input tools for mobile fields like date, email and phone.HTML5 is also used for better markup.

  • Symfony Framework

Drupal 8 uses Symfony and this opens access to a large set of external libraries while was improves the PHP syntax of Drupal.

  • Module Readiness

Many Drupal 7 contributed modules are now in Drupal 8 core itself like views module (In Drupal 7 views module is in contributed module list but in Drupal 8 it is in core).So there is no need to install those modules in Drupal 8.

  • Twig Template

Drupal 8 includes the flexible, fast, and secure template engine for PHP called Twig. With Twig, templates are now written an easy-to-learn syntax which brings several simplifications and greater security.

  • Low Cost

Building a website with Drupal 8 is less expensive than using any of its earlier versions, also because eventually you will need to upgrade it to Drupal 8 in a short span of time.

  • Quick Edit

Quick edit tool is one of the advantage in Drupal 8.We can easily edit text directly from the front-end of your site.

  • Multi-language support

Drupal 8 has built-in multilingual feature and thus you can easily translate anything in the system using built-in user interface. Drupal is great for building multilingual websites and this feature will benefit both end users and the Drupal developer to reach greater audiences on both sides.

With merits we have some demerits as well. Here are the Drupal 8 demerits…

DEMERITS

  • Symfony

Drupal 8 uses Symfony and this means the developers have to retrain themselves to adjust to the changes.

  • Drupal 8 Migration

There is no continuity/upgrade path from Drupal 7 to Drupal 8 . So the sites have to be rebuilt completely.

  • Contributed Modules

Drupal 8 Contributed modules are less when compared to Drupal 7. All the existing Drupal modules have to be upgraded to work on Drupal 8.

Drupal 8 is highly scalable, flexible and customizable that makes Drupal the open source CMS platform that more and more companies, small, medium and large enterprises, are adopting because of the features and functionality it offers them, but also its easy to maintain and less likely to break down over time.

Drupal developers can create custom pages using custom templates and routing in Drupal 8. Follow Drupal coding standards. Keep modules in root directory as given below.

modules/custom
modules/contrib

In custom folder contains our own custom modules. In contrib folder contains Drupal contributed modules.

Custom Module

 

Create a custom module

Module name: example

Info.yml

Drupal 7 - example.info (module_name.info) to store metadata about the module.
Drupal 8 - example.info.yml (module_name.info.yml) to store metadata about the module.

Path: modules/custom/example/example.info.yml

Example:

name: Example Custom Module
description: 'Provides a custom functionality' 
type: module 
core: 8.x 
package: Custom

routing.yml

Drupal 7 - Have hook_menu() to declare the path.
Drupal 8 - Create the routing.yml file.

The path of the content will be defined in example.routing.yml

Path: modules/custom/example/example.routing.yml

Example:

example.icecream_list_page:
  path: '/icecream/list'
  defaults:
    _controller: '\Drupal\example\Controller\IcecreamController::icecreamPage'
    _title: 'My Custom Icecream Page'
  requirements:
    _permission: 'access content'

Explanation about Routing code

example.icecream_page - machine name of the route
path - It gives the path to the page on the site. Note the leading slash (/)
defaults - It describes the page and title callbacks
  IcecreamController: Controller class name and it should be the file name of controller
    icecreamPage: Method Name
requirements - It is a condition to be displayed under the particular page. Can specify modules, permissions that must be enabled.

Page implementation

IcecreamController.php

Drupal 7 - Have .inc or .module file to define the method.
Drupal 8 - Create the Icecreamcontroller.php file.

The path of the content will be defined in Icecreamcontroller.php

Path: modules/custom/example/src/Controller/IcecreamController.php

<?php

/**
 * @file
 * @author Anitha
 * Contains \Drupal\example\Controller\IcecreamController.
 */


namespace Drupal\example\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Provides route responses for the example module.
 */
class IcecreamController extends ControllerBase {

  /**
   * Returns a simple page.
   *
   * @return array
   *   A simple renderable array.
   */
  public function icecreamPage() {
    $element = array(
      '#markup' => 'Frame all your needed contents',
    );
    return $element;
  }

}

After clearing the cache and see your custom page.

Features, Functions & Benefits

  • Can easily attach a theming function i.e  and/or tpl.php to a URL path/pattern.
  • Integration with the Context module Note : use custompage_region_tile($region_name) to include regions in custom pages, but not template variables!
  • Better for SEO and other presentations
  • To do package both data collection functions and an initial theme in a module
  • User-interface enhancement that will allow inline editing of the aggregated content items such as nodes and views on a custom page itself
  • Can do Custom Page to include a node with nid in site's default language and will know to swap it with the translation node when language is switched.

What is Twig?

Twig is a faster, and more secure template system than PHP. Twig is brought by a wider PHP world. Twig was built  by SensioLabs, the creator of Symfony2 framework. Drupal 8 is using Symfony2 to overhaul its codebase. Twig was the right choice to use for Drupal themes.

Using Twig in Drupal

Twig is the default templating engine in Drupal 8.

One of the results of this change is that all of the theme_* functions and PHPTemplate based *.tpl.php files have been replaced in by *.html.twig template files.

Comparison of PHP template & Twig theming

1. Docblock

PHP Template

<?php 
/** 
 * @file
 * File description
 */
?>

Twig

{# 
/** 
 * @file
 * File description
 */
#}  

File Names

PHP Template file : node--article.tpl.php
Twig file : node--article.html.twig
PHP Template function : page.tpl.php
Twig file : page.html.twig

Variables

You can use a dot (.) to access attributes of a variable (methods or properties of a PHP object, or items of a PHP array), or the so-called "subscript" syntax ([]):

{{ user.name }}
{{ user['name'] }}

Printing a variable

PHP Template

<div class="content"><?php print $user; ?></div>

Twig

<div class="content">{{ user }}</div>

Printing a hash key item

PHP Template

<?php print $user['#item']['alt']; ?>

Twig

{{ user['#item'].alt }}

Assigning a variable

PHP Template

<?php $new_var = $content->comments; ?>

Twig

{% set new_var = content.comments %}

Assigning an array

PHP Template

<?php $arguments = array('!author' => $author, '!date' => $created); ?>

Twig

{% set arguments = {'!author': author, '!date': created} %}

Setting Variables

You can assign values to variables inside code blocks.

{% set user = 'ram' %}
{% set num = [1, 2] %}
{% set ral = {'foo': 'bar'} %}

Conditionals

PHPTemplate

<?php if ($content->comments): endif; ?>

Twig

{% if content.comments %} {% endif %}

PHPTemplate

<?php if (!empty($content->comments)): endif; ?>

Twig

{% if content.comments is not empty %} {% endif %}

PHPTemplate

<?php if (isset($content->comments)): endif; ?>

Twig

{% if content.comments is defined %} {% endif %}

PHPTemplate

<?php if ($count > 0): endif; ?>

Twig

{% if count > 0 %} {% endif %}

Filters

Check_plain:


PHP Template

<?php print check_plain($name); ?>

Twig

{{ name|striptags }}

Translate
 

PHP Template

<?php print t('Navigate'); ?>

Twig

{{ 'Navigate'|t }}

Implode a list

PHP Template

<?php echo implode(', ', $regions); ?>

Original Twig:

{{ regions | join(', ') }}

Drupal 8 Twig:

{{ regions }}

How to enable debugging?

  1. Locate your site's services.yml file, likely located in sites/default/services.yml
  2. Edit the services.yml file and enable one or more of the debugging options defined below.

Parameters:

  twig.config:
    debug: true

Dump

The dump function dumps information about a template variable. This is mostly useful to debug a template that does not behave as expected by introspecting its variables:

{{ dump(user) }}


In an HTML context, wrap the output with a pre tag to make it easier to read:
 

{{ dump(user) }}

Empty

Determine whether a variable is empty:

{# evaluates to true if the user variable is null, false, an empty array, or the empty string #}
 

{% if user is empty %}
    ...
{% endif %}

Advantage of using Twig

Concise: The PHP language is verbose and becomes ridiculously verbose when it comes to output escaping:

<?php echo $variable ?>
<?php echo htmlspecialchars($variable, ENT_QUOTES, 'UTF-8') ?>
{{ variable }}
{{ variable|escape }}
{{ variable|e }}         {# shortcut to escape a variable #}

Template oriented syntax

Twig has shortcuts for common patterns, like having a default text displayed when you iterate over an empty array:

{% for region in regions %}
    * {{ region.name }}
{% else %}
    No regions have been found.
{% endfor %}

Full featured

Twig supports everything you need to build powerful templates with ease such as multiple inheritance, blocks, automatic output-escaping, and much more:
 

{% extends "sample.html" %}
{% block content %}
    Content of the page...
{% endblock %}

Functions

Functions can be called to generate content. Functions are called by their name followed by parentheses (()) and may have arguments.

For instance, the range function returns a list containing an arithmetic progression of integers:
 

{% for i in range(0, 3) %}
    {{ i }},
{% endfor %}

Twig: Fast Template

Using Twig will accelerate the performance in Drupal 8. In order to achieve the best speed possible and save time during Drupal development, Twig compiles templates down to plain optimized PHP code.

The overhead compared to regular PHP code was reduced to the very minimum.

A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/elseif/else), for-loops, as well as things like blocks. Control structures appear inside {% ... %} blocks.

For example, to display a list of users provided in a variable called users, use the following tag:

Example

<h1>List</h1>
<ul>
    {% for region in regions %}
        <li>{{ region.name|e }}</li>
    {% endfor %}
</ul>

Example

The if tag can be used to test an expression:

{% if regions|length > 0 %}
    <ul>
        {% for region in regions %}
            <li>{{ region.name|e }}</li>
        {% endfor %}
    </ul>
{% endif %}

Comments

To comment-out part of a line in a template, use the comment syntax {# ... #}. This is useful for debugging or to add information for other template designers or yourself:

{# note: disabled template because we no longer use this
    {% for region in regions %}
        ...
    {% endfor %}
#}

 

Drupal is one of the most popular open source content management system written in PHP and MySQL. Its functionality and usability are far greater than any other system, as it combines ingenuity with simplicity. When you want to build a high performance website, choose Drupal as it is highly flexible and scalable. Complex functionality and dynamic web pages can be developed using many out-of-the box modules provided by Drupal and customized according to your requirements.

Drupal development provides so much, but people make some common mistakes. Avoid these 10 costly mistakes:

1. Wrong folder structure

Using a wrong folder structure and installation of themes and modules at the root levels is a major mistake. Follow the right directory structure to the themes and modules as it will be hard to upgrade and debug.

2. Excessive coding

Avoid excessive coding on the site to implement the required functionality and use the Drupal modules to achieve the goals. Drupal provides core and contributed modules to solve most of the problems. But Drupal developers need to assess the risks associated with the beta or alpha version of modules as they might identify the deficiencies.

3. Hack core files and themes

Hacking the core files and themes makes your site vulnerable to hacking and it becomes almost impossible to apply security updates on your site. So don’t hack core.

4. Wrong module configuration

You must learn about the modules and its interdependencies before you configure and install on your site. Sometimes wrong configurations can lead to bugs or risks of security issues on your site.

5. Inefficient performance

Inefficient performance leads to increase in load time and leaves your site visitors frustrated. Aggregate CSS and Javascript files, configure caching and remove unused modules which will maximize the site performance.

6. Not backing up site

Take backups before making major updates or upgrades to their site. This will restore all your data in case of a major issue during updates or in case of data loss. This will also save precious time.

7. Not W3C-Compliant

Not following the w3c coding standards and guidelines is one of the major mistakes. Following the W3C guidelines ensures error-free and accurate coding.

8. Not implementing security policies

Not providing the suitable roles and permissions on your site can affect your site security. Always ensure that you authorize roles and permissions to users and no one is exploiting your site.

9. No anti-spam control

Always safeguard your site with anti-spam control measures, otherwise your site will be flooded with spam content. So take necessary precautions and enable spam control in comments and content.

10. Not selecting the right hosting service

You have done all the hard work, but selected a wrong host for your site. Your site passes through three different phases - development, deployment, and maintenance. Always use version control system VCS and keep your site (code and modules) up to date and select the right host who can handle spikes in your site traffic.

Subscribe to Drupal Development
 

start with anubavam today

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

Request Quote