How to Write PHP Unit Tests for Drupal 8

We all know that PHPunit testing framework has been added into Drupal 8. More than that SimpleTest in Drupal 8 is deprecated now. So let’s learn about, how to write the PHPUnit test for our requirement. The following Topics were covered during DrupalCamp Mumbai 2017 session. We are covering in the slides.

  • Why PHPUnit?

  • Things we need to know before writing PHPUnit Test Case?

    • Files Structure and namespace

    • PHPUnit Base Classes

  • How to write a PHPUnit Test?

  • Running PHPUnit tests

  • How to integrate with PHPStorm?

 

How to start your Drupal Contribution?

I am presenting at DrupalCamp Mumbai 2017 about the personal experience, about my Drupal Contributions. Will be covering following topics during the session -

  • What is Contribution?

  • Why Contribution is needed ?

  • What all are ways you can contribute to Drupal community?

  • What is important of contribution?

  • When  you can start the Contribution?

  • How can  you keep contribution going with your work?

  • What is the benefits of a contributor?

  • How to work on Issue queues?

  • How to select the issues?

  • Contribution, contribution and contribution

Stay tuned, will upload the slides next week.

Console your Drupal 8 Module Development

Drupal Console is a scaffolding tool built for Drupal 8 automatic code generation.  During this session will be doing live demo on creating module in Drupal 8 and showing how to take the  advantage of the Symfony Console Component. And we we will be covering  following topics during session at DrupalCamp Mumbai 2017.

  • What is Drupal Console?

  • Why Drupal Console?

  • How to speed up your drupal 8 development using Drupal Console?

  • How to create a new console command?

  • How to create a custom module using Drupal Console?

Stay tuned, will upload the slides next week.

9 ways Unit Testing improves your product quality

Testing and development have forever been in war. It is obvious that Testing helps reduce errors and redundant tasks, but the amount of effort required to be put be each one is different and there is where the pressure to implement unit testing into the development process comes into action and actually makes more sense.

Testing helps to find out bugs and move the development of new functionalities. And unit testing validates that your functionalities work well in the best and worst of use cases.

unit testing

What freedom does Unit Testing give you?

1. Reduce Time

Piled up dev and QA cycles slow down legacy systems. Codes written without detailed tests make it easier to change codes making it difficult to stick to timelines

2. Flexible

Agility comes as a difficult thing with most legacy systems. Most of the times it becomes a burden to change codes on which applications and businesses run. Properly tested codes do very little to break existing functionality.

3. Quality Assured

To ensure that development teams do not release buggy codes so that QA doesn’t come up to be expensive and heavy on the pocket, unit testing helps to avoid this exact scenario where we take prevention to be better than cure. Unit testing helps to improve performance of product

4. Documentation

Test case scenarios are much better than 1000s of lines of technical documentations. Developers need to work with code examples and snippets rather than documents which hold a lot less practical value.

5. Practical Value

Unit test gives you much needed practical visual information whether that button is giving you the kind of result its supposed to when you click on it. The best thing about unit tests is that the documentation also shows  how your code is supposed to behave. It is like e reference point and standard for your teammates, that come in handy very often.

6. Scalability

Testing helps in easy change of codes because you know exactly at what point it will break the functionality. With extensive  test coverage it is easier to explore new functionalities and features without fearing about introducing new bugs, you know where to roll back to. Legacy systems that have poorly tested units keep making systems more bulky to the point of breakage and it becomes utterly difficult to scale the platform.

7. Code Refactoring

Testing helps in restructuring existing code —changing the factoring— without changing its external behavior. It speeds up system without any visual changes so that you can changes the way your program is designed but with little or no effect to existing functionalities.

8. Tests actually help Programmers

Ideal scenarios are very very different than practical ones and real world issues make it difficult to deal with them. Difference in operating systems, mini and micro bugs, stupid rules often make peculiar errors which is avoidable with Unit Testing

9. Testing is way important than you think

Testing is considered to be less important when you think about development and are given to the less experienced programmers. But coming up with various test scenarios can be tough too. Testing is not ticking on a written checklist, it is not  monkey job. In a lot of cases writing automated tests is harder than coding and requires experience.

Testing tends to slow you down if you are doing units testing class-by-class or methods. You need to invest good time to write some quality tests. But with time it becomes a more trusted method because you worry less about breaking existing codes while you add new functionalities.

"Imperfect tests, run frequently, are much better than perfect tests that are never written at all"

What helped to write this blog : Stackoverflow, Unit Testing

How to create .info file for themes in Drupal 7

The .info files is most important part of Drupal themes. The .info file in a Drupal theme configures the theme. Drupal 7 Support PHPTemplate engine which is needed to powered theming system. This file has a configuration function and syntax similar to a .ini file. 

The .info file is a collection of static text file, used to define and configuring a theme. Each line in the .info file has a key-value pair with the key on the left and value on the right hand side, with an "equals sign" between them (e.g. name = my_new_theme). Semicolons are used to comment out a line. As we do follow # symbol or /* */ symbols to comment out or to provide developer comment. Some keys uses a syntax with square brackets for building a list of associated values, represent to as an "array". If you are not aware with arrays, have a look at the default .info files that come with Drupal and read the explanations of the examples that follow. Even though the .info file is not natively opened by an Application, you can use TextEdit or Notepad on a Windows computer in order to view, edit, and save your changes.

Let’s look at an example of what you might have found in an .info file

name = My Theme
description = A description of my theme
core = 7.x

# Add a base theme, if you want to use one.
base = mybasetheme

# Define regions, otherwise the default regions will be used.

regions[header] = Header
regions[navigation] = Navigation
regions[content] = Content
regions[sidebar] = Sidebar
regions[footer] = Footer

 

# Define which features are available. If none are specified, all the default 
# features will be available.

features[] = logo
features[] = name
features[] = favicon

# Add stylesheets

stylesheets[all][] = css/reset.css
stylesheets[all][] = css/mytheme.css
stylesheets[print][] = css/print.css

 

# Add javascript files

styles[] = js/mytheme.js

 

 

There are some of the most needed information that need to be in every Drupal .info file

name – This should be human-friendly name that will be displayed on the theme select page.
and it can be set independently from the internal "machine" readable name. This imposes fewer restrictions on the allowed characters.

name =  A fancy theme

description (recommended) – This is a short description of the theme that helps identifying it on the theme select page. This description is displayed on the theme select page at "Administer > Site building > themes".

description = multi column row for fancy theme

core – earlier version of Drupal 6.x .info file should state which major core version of Drupal it is compatible with, just  to avoid compatibility issues. The value set here is compared with the DRUPAL_CORE_COMPATIBILITY constant. If it does not match, the theme will be disabled.

But in Drupal 7.x packaging script automatically sets this value based on the Drupal core compatibility setting on each release node. So people downloading packaged themes from drupal.org will always get the right thing. 

On top of that we also have other key value pair which is needed optionally.

core= 7.x

version (discouraged)
The version string is automatically be added by drupal.org when a release is created and a tarball packaged. So you may omit this value for contributed themes. However, if your theme is not being hosted on the drupal.org infrastructure, you can give your theme whatever version string makes sense.

version = 1.0 

base theme
When you are about to create a new theme in that scenario Sub-themes can declare a base theme. This allows theme to inherit, reusing the resources from the "base theme" will cascade and be reused inside the sub-theme. Sub-themes can declare other sub-themes as their base, allowing multiple levels of inheritance. Use the internal "machine" readable name of the base theme. 

base theme = bootstrap

region
If you overriding regions in D7, you are obliged to declare the line regions[content] = Content. If you want any of the default regions in your theme, you have to declare them as well.

In Drupal, we have block regions. Block regions are dynamic content areas that hold different content (block) that you can set through the Drupal administrator dashboard. The important thing is, these regions are set in the .info file of a Drupal theme.

regions[left] = Left sidebar
regions[right] = Right sidebar
regions[content] = Content
regions[header] = Header
regions[footer] = Footer

The above is a list of default regions in Drupal 7. To use those regions in the theme’s page.tpl.php file, all you need to do is something similar to this:

/* Display blocks in "Left sidebar" */

Features
In Drupal 7, features are not inherited from the base theme. If you are using features other than the default, you should copy the features declarations from the parent theme's .info file.
Various page elements output by the theme can be toggled on and off on the theme's config page. The "features" keys control which of these check boxes display on the theme's config page. 

The example below lists all the available elements controlled by the features key.

Drupal 7 features

features[] = logo 
features[] = name 
features[] = slogan 
features[] = node_user_picture 
features[] = comment_user_picture 
features[] = comment_user_verification 
features[] = favicon 
features[] = main_menu 
features[] = secondary_menu 


Stylesheets
To Override inherited style sheets: Specify a stylesheet with the same filename in the sub-theme. For instance, to override style.css inherited from a parent theme, add the following line to your sub-theme's .info file:

stylesheets[all][] = style.css

On drupal 6.x version themes default to using style.css automatically and could add additional stylesheets by calling drupal_add_css() in their template.php file. Whereas in Drupal 7, themes no longer default to using style.css if it is not specified in the .info file.


Scripts
All JavaScript files defined in the parent theme will be inherited.

Overriding inherited JavaScript: Specify a JavaScript file with the same filename in the sub-theme's .info file. For instance, to override script.js inherited from a parent theme, add the following line to your sub-theme's .info file:

On drupal 6.x version themes could add Javascripts by calling drupal_add_js() in their template.php file. if a file named script.js exists in the theme directory then it is automatically included. However, in Drupal 7.x version, this behavior has been changed again so that script.js is only included if it has been specified in the .info file:

scripts[] = myscript.js 

Conclusion: Drupal theme development could be a bit complicated at first time, but learning about Drupal themes in general and learning about what each file does and How functionality work and what type of function call does it make could help you a lot to set you on the right direction to becoming a Drupal Front End developer.
 

How to make Drupal Custom Templates for Content Types in Drupal 7

Drupal Custom Templates go a long way to help UI developers in Drupal, it gives an edge to easily create drupal custom pages with new templates and get the desired HTML output. You don't have to rely on any templates because it might not match up with the vision, requirement or content and expands the limits set by Drupal themes.

From the Beginning of time while doing Drupal theme development we prefer to use the own custom template to render page/block/ field/view. Overriding a template file is one of the common tasks for a front-end developer, but depending on the base theme used it’s not always clear how to go about doing it.

Most Drupal themes come with a minimum of 3 default template files: html.tpl.php, page.tpl.php and node.tpl.php. And many other template files used to control the display of more specific elements such as comments or individual fields. Each of these files can be overridden for a specific condition simply by creating a new drupal tpl file in the theme folder with the correct name. These file names are called “drupal template” and there is a standard set of these suggestions built into Drupal and listed in the documentation as Drupal Template Suggestions( drupal theme hook).

Page Template Per Content Type

The most common and overriding concept we used to follow is to not includ in the default list is the page.tpl.php override based on the content type being displayed. There is a node.tpl.php override based on the same condition which leads to confusion as to where the page override exists. On top of that, themes like Zen add this type of override to the Template Suggestions, which leads those using Zen to believe that this is part of the default list. Check the theme documentation to see if this override has been added to the Template Suggestions by the theme. If it hasn’t, you need to add it manually.

The process is straightforward. We can create additional Template Suggestions simply by adding them to the ‘theme_hook_suggestions array in our template.php file.

Open the template.php file in your theme for editing.
Look for a function called yourthemename_preprocess_page (replace the yourthemename with your theme’s name).
If this function already exists, you will need to add the if statement to the end of the function just before the closing bracket. Otherwise, you’ll need to create a new function to look like this:

function THEME_preprocess_page(&$variables) {
  if (isset($variables['node']->type)) {
   // If the content type's machine name is "my_machine_name" the file
   // name will be "page--my-machine-name.tpl.php".
   $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
   }
} 


Now you can create a template file called page--content-type.tpl.php and all nodes with that type will use the new template file.

Filename Notes:

Use two dashes after the word ‘page’ in the filename.
If your content type is two or more words, replace the underscore ( _ ) with a short dash ( - ) in the content type machine name.

Using page--content-type.tpl.php we have the feasibility to create multiple layouts for each and every bundle. And on the same layout, you can add design/functionality of your choice.

How to send custom formatted HTML mail in Drupal 8 using hook_mail_alter()

As you can understand from name itself it’s basically used to Alter an email created with drupal mail in D7/ MailManagerInterface->mail()in D8.  hook_mail_alter() allows modification of email messages which includes adding and/or changing message text, message fields, and message headers.

Email sent rather than drupal_mail() will not call hook_mail_alter(). All core modules use drupal_mail() & always a recommendation to use drupal_mail but it’s not mandatory.

Syntax: hook_mail_alter(&$message)

Parameters

$message: Array containing the message data. Below are the Keys in this array include:

  • 'id': The id of the message.
  • 'to': The address or addresses the message will be sent to. 
  • 'from': This address will be marked as being from, which is either a custom address or site-wide default mail address.
  • 'subject': Subject of the email to be sent. Subject should not contain any newline characters.
  • 'body': An array of strings containing the message text. message body created by concatenating individual array strings into a single text string.
  • 'headers': Associative array containing mail headers, such as From, Sender, MIME-Version, Content-Type, etc.
  • 'params': An array of optional parameters supplied by the caller of drupal_mail() that is used to build the message before hook_mail_alter() is invoked.
  • 'language': The language object used to build the message before hook_mail_alter() is invoked.
  • 'send': Set to FALSE to abort sending this email message.

Why i am discussing on hook_mail_alter() ?

Recently i was doing one of the Drupal 8 project where client was looking for formatted HTML mail that also works for contact form. So whenever an anonymous user fill up and submit the contact form, It triggers an automated mail to the admin user. If you ever get a chance then just look at that weird formatted Email. Mail related to contact form is being triggered from core contact module in D8.

Just to alter the email format in Drupal 8 we have decided to write a custom module using hook_mail_alter() which alters the outgoing email message using drupal_mail().


Let’s start with code:

To implement hook_mail_alter() whether you can write your own custom module or put it in any of the custom module.

Sample Source code:

/**
 * Implements hook_mail_alter().
 */
function mymodule_mail_alter(&$message) {
  if (isset($message['id']) && $message['id'] == 'contact_page_mail') {
    /** @var \Drupal\contact\Entity\Message $contact_message */
    $contact_message = $message['params']['contact_message'];
    // Get sender's name.
    $sender_name = $contact_message->getSenderName();
    // Get sender's mail.
    $sender_mail = $contact_message->getSenderMail();
    // Get subject.
    $subject = $contact_message->getSubject();
    // Get message.
    $message_body = $contact_message->getMessage();
    // Get the value of "field_request" field.
    $request_value = $contact_message->get('field_request')->getValue();
  }
}

In Above source code  as you can see that we have added conditional statement so the changes will be impact only on specific mail.  

$message['params']['contact_message']: The message entity stored in the variable and it contains all the values from the contact form. Where contact_message is the type of entity. We can also fetch all the custom field value using get() method.

Source code

hook_mail_alter is solution to customize your mail body send through drupal mail. In this blog i have shared my idea of how can we send custom HTML formatted mail which triggers from Core drupal 8 contact form.  
 

4 Big Data Strategies That Will Transform Media Businesses

Media companies are facing new business challenges with increased pressure to execute new digital production and utilise big data strategies to monetise the opportunities at hand. The media companies need to adopt digital and data strategy, not only to move towards profitability but also to achieve operational efficiency.

Adopting a Multi-distribution Model

In order to deliver content for a variety of platforms/devices, it is critical that companies to establish platforms that can scale up and support this multi-distribution model. Most of the media companies rely on extensive networks of freelancers and subcontractors, thus media companies need resource scheduling toolsets to manage the same.

Insights

Utilising a variety of data sources and operational intelligence  can help media companies gain a better understanding of future customer demands. These data sources include social media, web browsing patterns, advertising response data, demographic data etc. to anticipate demand for more efficient content management, revenue generation and overall profitability. The rise in new tools and analytics, such as cohort are helping drive a better understanding of audience preferences.

Personalised Experiences

Through the captured data, customer needs and wants can be analysed and customised offerings are being offered to enhance customer experiences. Big data and operational analytics is also used to determine the business opportunity linked to the acquisition of new content and gain more advertising revenue growth through better targeting.

Data Management System

Big data management systems are needed to be deployed to analyse different forms of data and to ensure that the business can become more agile. There is always a need to deploy the right tools and capabilities to the right users, thus an optimal technology needs to be chosen depending on the data needs; bridging the gap between data collection and application.

For most publishers of online content, striking the right balance of advertising and operations revenue is an objective, and can be achieved with capturing and analysing accurate big data and analytics.

Combining analytics with operational intelligence will yield good results in the long run. Today’s business environment requires flexibility, speed and accuracy and media companies are making considerable investments in data capabilities to achieve agility. As data volume, velocity and variety grows, investment in data infrastructure and architecture becomes a necessity. By using operational analytics, and coupling it with big data along with available resources will drive the business to achieve efficiencies and deliver better customer experiences.

 

Installation & Configuration of Apache solr server 4.6 on Windows Machine

I was working on one of the projects where the client was not satisfied with the existing drupal search as it was not able to meet their requirements on the site. So they decided to go with Apache Solr.

Those who are not aware of what exactly it is, I would like to give them a very basic introduction or a description of what it does.
  

Apache Solr is an open-source search platform built upon java library. It’s one of the most popular search platform used by most websites so that it can search and index across the site and return related content based on the search query.  

For more detailed information, please visit http://lucene.apache.org/solr/

So let’s begin with solr installation. To install Solr on the windows system, the machine should have [JRE] Java Runtime Environment with the right version. 

Step 1: Go to cmd prompt and check for JRE with correct version.
If JRE is available in your system it will show you the version. If not then you have to install JRE 
 

JRE version

Step 2: Download require solr version from below url 
https://archive.apache.org/dist/lucene/solr/
For this tutorial i have downloaded 4.6.1 from https://archive.apache.org/dist/lucene/solr/4.6.1/  Download solr-4.6.1.zip  File

solr 4.6.1 Download

Step 3:  Extract the Zip folder in your machine.now go to extarcted solr folder. Get inside the example folder and execute the command

java -jar start.jar

Solr Folder structure

As soon as you run the above command solr will start with default port 8983. That can be accessible on localhost:8983/solr/#/

This will install Solr and run in the background. By default it uses the port number 8983.
You can change default port number to one of your choice. 

solr UI

Step 4: To Configure solr with Drupal 7.x Download solr from https://www.drupal.org/project/apachesolr  download the recomended version and install as we do normal module installation.

Step 5:  Go to \apachesolr-7.x-1.8\apachesolr\solr-conf\solr-4.x copy all the files to solr server directory [solr-4.6.1\example\solr\collection1\conf\] and replace them with existing files. 

After replacing your file should look like.
After replacement file structure

Now your solr admin page look like 


Configured solr page

Step 6: So we are almost done with solr server setup. Let’s configure on module level

To do this we need to go to solr setting page /admin/config/search/apachesolr/settings
Fill up mandatory detail like solr server url and  description and hit on Test Connection button.
 

Sol Configuration in Drupal

Step 7: Almost done with solr server setup and configuration, let’s do indexing by visiting default index page admin/config/search/apachesolr. 

Solr default index page

The above steps would cover up solr server installation in your windows machine with configured D7 Apache solr module. 

Conclusion: The main objective of this blog is to let the windows user to install and configured solr server and also allowing them to configure with Drupal 7. In present situation we already have variant of solr server on the web but i have recommended to use 4.6.x for Drupal 7. 
 

How Media Companies Are Balancing Big Data and Operational Efficiencies?

The business environment in publishing and media industry is being disrupted by the digital collision. The explosion of big data along with availability of technology, analytics and social media, are the new facets of customer engagement for the industry. This explosion is not only impacting operations of silos but also other components of the business, as they are involved in generating more data than ever before in structured as well as unstructured forms. Media companies are increasingly using the internet as a means to deliver content, resulting in increased data velocity and aggregated data volumes. This current digital turbulence presents massive opportunities – and big data has now become a foundation of future success.

While going digital, big data and analytics significantly impacts decision-making, as there will always be a need to switch to real time data resulting in increased scope and scale of work. For instance, the company Springer, a leading publisher of scientific journals and books; decided to go digital and provide online offerings, thus; making all content easily searchable and accessible on all devices. They used data tools to provide search results based on geographical locations and also real-time data along with trending topics. Not only they made their journals easily accessible but also gained 95% of their revenue from online business. This wouldn’t have been possible without using big data.

Media companies are now profiling customers using both enriched internal CRM data and public data from online content delivery platforms and social networks. Customer has now taken a center stage in real-time with data-driven reporting. Real-time data mining and analytics are revealing customer needs and this helps the companies to tailor content dynamically, resulting in better decision making and content provisioning.

When companies are handling so much of data, media asset management becomes important and meta-tagging of media assets becomes necessary. For, instance, British Broadcasting Company(BBC) generated more than two petabytes of data during the 2012 Olympics and the big challenge was to deal with the enormous data that was to be created; which included more than 10,000 individual pages covering over 10.000 athletes, 200 teams and 500 disciplines. It became necessary to incorporate big data in their strategy. As a solution, the BBC opted for generating these pages automatically and enriched it with metadata. This metadata was also used to automatically generate more new pages. This approach worked to handle huge amounts of data with an average of 25.000 transactions per second.

The challenge the media companies face is to access, analyze, and manage vast volumes of data and improve operational efficiency as well as performance. Using big data in an appropriate way can help transforming these challenges into opportunities.

Image Courtesy

 

 

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch