Most Commonly Used hooks in Drupal 7

Before I begin with hooks, I am sure that you must be aware of the Drupal hook system. What is hook? How modules interact with the core code of Drupal? How hooks make it possible for a module to define pages, content, bundle, entity, menu, region, table, url etc? In this article I will be re-introducing you to the hooks and if you are looking for more information on the hook system then my suggestion is to go through Understanding hook system for Drupal module

First, I would like to give a small summary on hooks. A hook is a way to place a piece of your own custom code to be run by Drupal. Using hooks, you can ask Drupal to run a piece of code when a node is viewed/edited/deleted. hooks are conceptually related to method. They represent standard ways of interacting with data structures. Also many hooks are state aware, and do different things depending on what exactly is happening at the time the hook is called. 

What Drupal's Hooks API does: 

A Hook is a PHP function in a custom module that executes code. 
The Hooks API allow you to create your own hooks that other modules can access. It provides a common naming standard for hooks and allows modules to interact with other modules. 

As a Drupal Developer, you come across plenty of hooks used in core , contributed & custom module very often. 

There are hooks that are used more often,These common hooks include:

hook_help - Create help text associated with your custom module. 

Description: This hook provides the necessary help and information about module. To implement this hook, you need to replace “hook” with your module’s name and create a function in the module file with that name. The page-specific help information appears on help page. The module overview help information is displayed by the Help module. It can be accessed from the page at admin/help or from the Modules page.

hook_help($path, $arg)

Parameters 

$path: The router menu path, defined in hook_menu(), for the help that is being requested; e.g., 'admin/people' or 'user/register'. 

$arg: An array corresponds to return value of the arg() function, for modules that want to provide help that is specific to certain values of wildcards in $path. 

hook_permission - Create permissions associated with your module. 

Description: This hook gives permissions to the module, so they can be selected on the user permissions page and used to Allow or Restrict access to the module so that certain roles can access pages, i.e. the 'Administrator' to change settings or certain role to view the page. It returns nested array.

hook_menu - Define menu items and page callbacks. 

Description: Adding a module configuration page to Drupal menu is an important task.This hook enables modules to register paths for URL handling. They can be used to register a link to be placed in a menu. A path and its attributes called as "menu router item". This hook is rarely called (for example, when modules are enabled), and its results are cached in the database. 

hook_menu_alter - Alter the data being saved to the {menu_router} table after hook_menu is invoked. 

Description: This allows us to alter elements in Drupal's menu system. The primary links, secondary links, tabs and page callbacks can be altered in this way. 
Alter the data available in {menu_router} table after hook_menu is invoked. 
The menu definitions are passed in by reference. Each element of the $items array is one item returned by a module from hook_menu. 

hook_cron - Used for carrying out actions when the cron runs. 

Description: hook_cron() provides a powerful, simple, and useful tool for background task processing independent of page requests. 
The Drupal will call this hook whenever a cron run happens.Tasks managed by hook_cron() are database maintenance, backups, recalculation of settings or parameters and automated mailing.

Short-running tasks can be executed directly whereas Long-running tasks could time out, so that we should use queue API instead of executing the tasks directly. To do that first we need to define one or more queues via hook_cron_queue_info(). Then, add items that need to be processed to the defined queues.


hook_form_alter - Perform alterations before a form is rendered. 

Description: Changing / Adding  element to the existing form structure is One of the popular use of this hook, the node object can be accessed at $form['#node']. One of the benefits of using the Form API to construct forms is that any module can alter any other modules form. 


hook_form_alter(&$form, &$form_state, $form_id) 

Parameters 

$form: Nested array of form elements. 
$form_state: Current state of the form. 
$form_id: String representing the name of the form itself.
 

hook_form_FORM_ID_alter - Provide a form-specific alteration instead of the global .

Description: This  hook can do similar task as compared to hook_form_alter, only difference is that instead of making global hook_form_alter(), it uses form specific hook. Applied only to specif form. Rather than checking form id or using long switch statement to alter individual form.

Parameters 

$form: Nested array of form elements. 
$form_state: A keyed array containing the current state of the form. 
$form_id: String representing the name of the form itself.

hook_theme - Register a module (or theme's) theme implementations. 

Description: Reason behind implementing hook_theme under a custom module or theme is to register theme implementations which specify how a particular array should be rendered as HTML.

We've now hooked our module into the theme system. Let's look at what these items do: 

'my_custom_template' => array(): This is the name of Template. 
'template' => 'custom-page': This key-value pair will call to a new template file that will look like this: 'custom-page.tpl.php'.

hook_theme($existing, $type, $theme, $path)

Parameters 

$existing: An array of existing implementations that may be used for override purposes. This is primarily useful for themes that may wish to examine existing implementations to extract data (such as arguments) so that it may properly register its own, higher priority implementations. 
$type: Whether a theme, module, etc. is being processed. 
$theme: The actual name of theme, module, etc. that is being being processed. 
$path: The directory path of the theme or module.

7 Things you need to know before expanding to a Multilingual Website

For a Digital Media website, expanding business to another language is a quite challenging and tough task to deal with. It makes you re-evaluate your CMS . A lot of questions come forward while you take the decision. Firstly Why? But now that you know you want to translate, you think, What all should we translate? How will we handle pages in default language? What components do we add? What services to use and how to maintain pages?

A major chunk of content these days is written, managed and stored with the help of a CMS or Content Management System (CMS). Selecting the right CMS at the beginning of expansion into a multilingual site ensures that the website and its contents are effectively managed and displayed right from the beginning.

# 1 What  is the potential of a Multilingual Website?

It is no more a shocker that the global organizations which manage Digital Properties support multiple websites in multiple languages which is much more difficult done than said. In today’s market there exists a lot of choices for one to select a CMS,but very few which allows easy editing of content and full edit options, most importantly ease of use for the users. Drupal comes with powerful multilingual feature.

#2 When is Drupal the right fit for your need?

Drupal 8 comes with a ton of features to perfectly suit your best needs, it has evolved over time and has solved a lot of complexities from Drupal 7 and its Multilingual capabilities are come in-built in core. In my previous blog post, we discussed about the need of Multilingual website and the right time to go for it. In short When you have a media website with visitors from language background other than your default, it’s best to switch to a multilingual website to ensure you do not lose your business and have a continuous growth.

#3 Why Drupal is exactly what you need?

With a website which has the capability to shape itself to the language of choice across any platform is the need of the hour. Drupal 8 comes with this powerful feature which will enable your business to reach to a larger audience. It comes with a powerful multilingual feature which helps translation into regional content and local languages and can be easily implemented. The multilingual feature comes with more than 90 languages and is applicable to all fields, forms and messages. Not only this but it also comes with a built-in translational core. Assets, like files or images, can have be assigned to a language or shared.

The challenge with translating sites with Drupal is none. It requires very less manual work. Once you add more content, all of it is scalable, it can cope and perform under a demanding workload. A system which scales well will be able to maintain or even expand its level of performance or experience when tested by larger operational demands which media sites go through more often than any other sites.             

Multilingual Site

 

#5 What makes Drupal special for Multilingual Websites?

It is quite different than the popular CMS translation plugins. It doesn't make you waste time on creating new pages, new menus and so on. It also doesn't only translate "content", it lets you translate all things that you "see" on the front-end of your site (including text,forms, error messages and more). Drupal 8 hands out extensive multilingual features right out of the box. The admin interface has built-in translations.             

Translate all things

Translate all things

It is Multilingual first: Auto-detection of language and auto-downloading latest interface translations             

Multilingual first

 

# 6 What things allow translation?

Drupal 8 allows all components from configuration settings to menus, views and field values.  It allows user to select operations based on language options.            

Translatable entities

For content entities like taxonomy, nodes and users it is also possible to change visible language selector options to default or of another language.

#7 What are the Key Features?

Improved functionality of Multilingual is the another feature of Drupal8. With Drupal8 you can:

  • Multi-Translate all things in the system which has built-in user interfaces.

  • Build web pages with Views language filtering and block visibility.

  • Get automatic software translation updates from the Drupal community.

  • Add a language selector to your site

  • Auto-determine the visitors language.

  • Choose what not to translate

  • Install in 94 languages

  • Overview screen for translators, contextual translation tabs for site builders

  • Protected local, custom translations which are exportable

  • English can be removed, no more to be default

Having a website work it’s inside out in Multiple languages has never been smarter and more user - friendly

The team at Valuebound has experience of working on high-traffic multilingual Drupal websites. If you're looking for getting an understanding of how your website will do in Multilingual, let us know.

 

Learning about Form & Field Validation in Drupal 7

This article is to share my experience with Drupal CMS. It will be helpful , particularly for novice/beginner level Drupal programmers to build their knowledge block on Drupal framework. Even though you might be aware of a few functionalities mentioned, this article will guide you on the basics of ‘what should be used’, ‘when to be used’ and ‘why to use’.

I have started blogging again after a brief break to share my knowledge of Drupal. Before getting into any of the technical aspects, I would suggest you to try and understand the ‘How & why?’. This will help you concrete you knowledge about any form of technology. So let’s begin with a functionality instance of Drupal called “validation”. 

Terminology will be used in most of the forms where the end user has  the required data with self and is ready to validate the same before submission. It gives assurance that the data posted to table does not have any miscellaneous data. Proper validation of form data is important to protect your form from hackers and spammers.

Types of validations that we can perform on form:

Validate Drupal form using validate function

hook_form_alter() : By implementing hook_form_alter to the specific bundle and calling $form['#validate’][], it will list all of the validation functions for a given form. Here we can add our custom validation to the validation handler array using $form['#validate'][].

When you hit the node/add/* , you will find node_form_validate(), which is the core validator for node forms.

form validation tutorial 0

The above validate_handler would be useful when it comes to an existing node type, where the developer has full access to insert validation for a form using custom module.

Validate only Drupal form field element using custom function:

We don't need to add an entire form validation every time. We can add a validation handler for an individual form element using #element_validate. We can also construct our own element validators. 

To validate a specific field, we can use #element_validate, with the element specific validation function which will pass $form_state and $element.

Use a pre-defined validation handler to validate numbers/integers.

form validation tutorial 1

Instead of handling the entire form, #element_validate helps to trigger a specific field  validation and displaying custom error message.

Validate Only Individual form element with pre define validation handler:

Drupal has a lot of pre define validators. The only thing is that either we are not aware of it or we haven't used it before.
When you want to validate a number with a predefined handler, you don’t have to add the validation function as it already exists.

Drupal has already defined a handler that validates if the data is a number, called element_validate_number. So we need to add the following to our form element:

Just one line of code can handle validation. Here is a list of  pre-defined validation handlers.

  • date_validate - Validates the date type to prevent invalid dates (e.g., February 30, 2006).
  • element_validate_integer -Form element validation handler for integer elements.
  • element_validate_integer_positive - Form element validation handler
  • for integer elements that must be positive
  • element_validate_number - Form element validation handler for number elements.
  • password_confirm_validate - Validates a password_confirm element.


     form validation tutorial 2

     

An individual form element handler with pre define core function, does not allow you to write custom error messages. As of now there are a list of functions available to execute basic validation over form.

Validate function using _form_validate from drupal API

We can add custom handler to validate the data entered into the field.
NOTE: Name of the function. It is simply the name of the form followed by '_validate'. This is always the name of the default validation function.

form validation tutorial 3

Default drupal core provides hook to handle field validation. And the pattern is form_id_validate() where we can set our own message. 


Conclusion: Above methods are small pieces of validation towards entity and bundle field. Based on best practice and specific project requirement validation, handler should be used. 


GIT Source Code: https://github.com/xaiwant/D7validation/tree/master/article_rule

6 things to consider before you switch over to your new ECM system

Organized management and a good visual of your content gives you an edge over your competitors and this feeds the concern over when you should migrate to your new Enterprise Content Management (ECM) System . The whole process requires a huge capital investment and do not forget disrupting your business which can in turn spoil your customer’s digital experience. Before you go looking for a new ECM system to develop your new platform, you should consider an assessment of your current system that takes a comprehensive view of your current tools and processes. This assessment will cover a similar ground as the ECM system selection process and also gives the possibility that the best platform may be the one you already have.

If you go to a grocery store hungry, you will end up buying things you don’t actually need. Most smart people avoid this by making a list of essentials. When it comes to selecting a new ECM system, documenting your needs is an absolute necessity. Comparing your existing ECM system to the functionalities  you are hoping for, is a matter of magnitude. By considering each area carefully, your organization can make the best strategic decision possible and get the most value from the ECM system you implement. Now assessing the implementation is the matter of measuring this magnitude which we cover in the following six points:

  1. Integration of ECM system with your Business process

    The main aim of integrating your business with an ECM system would be to content-enable the business applications so that the latest and most accurate information is readily available.

    Unstructured content can be scattered across various repositories which can happen due to individual applications having their own stores for related information.

    Significant cost savings can be achieved when the core business applications are organized and content enabled. This improves efficiency(Fig 1.1) and reduces reliance on paper and also lowers physical storage.

    Business drivers for document and record management

    Fig 1.1: The most significant business drivers for document and records management (Source: AIIM, State of the ECM Industry 2011)

    Although the ability to organize and structure pages is not required now, it might be needed in future. Always look out for CMS which do not allow flexibility for such core tasks.

  2. Core ECM Capabilities

    As the company grows, so does the variety of content that needs to be archived and content that needs to be disposed off. A good ECM system should be able to manage the entire lifecycle of various content types and support other processes like search, retention and rendering associated with the content types and also let you define each step of the content’s lifecycle.

    Records Management and retention policies helps control the creation, classification, declaration, retention, and destruction of content and records, resulting in improved compliance, minimum litigation risk, and lower storage costs.

    Basic functionalities to consider include:

    • Search- full-text search, filtered search results for end-users to quickly find what they have authorized access to, and advanced search capabilities like custom search forms and metadata search.

    • Metadata, Classification and Taxonomies- Support for automated, manual and inherited metadata values on all types of content and classification of content based on these values.

    • Versioning-automatic tracking and storage of each file version along with auditing, archiving and the ability to revert to a previous version of a document if needed.  

    • Rendition support-the ability to automatically generate content in other formats (PDF, XML, HTML).

    • Compound document support – to allow smaller documents to be incorporated within a master or parent document.

  3. Ease of Access (multi-channel content creation & consumption)

    A good ECM system allows your employees or users to access information from various devices. These days it is important to make your information accessible through mobile devices. Whether it is for intranet, ethernet or mix of both, access to content in this context adds significant value.

    A CMS implementation has three primary requirements: developer’s needs, user experience and the content author’s needs to maintain the user experience.

    The user’s and developer’s needs usually become the focus of an ECM System implementation, but the process doesn't end when it goes live.

  4. Content Authoring Workflow

    The CMS of choice should also have expandable workflow capacity to meet the future needs of your business. Analyzing the workflow of your organization helps you select a better suited ECM System.

    If your authors face difficulty  working with your new ECM System, it’s implementation might not serve your purpose well. A discontent from the author community will affect the business as your system is starved of new content  and you might go through another cycle of a new CMS implementation.

    Encourage author adoption of the new ECM System by both training and considering various functionalities of your new ECM System that your authors require.

    These functionalities can be types of content that can be submitted, provision of author tools (eg: SEO, spell check, standard taxonomies, compliance tools, auto-complete of metadata items), a suitable permission model to hide irrelevant features from the author etc.

  5. Enterprise-Class Capabilities

    The ability of an ECM System to grow and adapt to your business’s growing needs in a way that it does not bring up limitations is one critical factor to be considered. Also, it should not add significant support costs in  future.

    You new ECM system is going to be the information backbone of your company and should meet certain requirements:

    • Scalability- It should be able to scale thousands of users and billions of content types and also manage the lifecycle of these information efficiently.

    • Security- Admin’s ability to define access to various types of information based on the type of user, different groups across the organization or an end user. A good ECM System will have data encryption and restrictions on database access to provide optimum level of security.

    • Managing,Auditing and Reporting- A unified administration has better manageability and lower costs. Having a lone platform that allows an admin to manage all the information, services and reports and logs from a single console reduces staffing requirements and improves compliance by eliminating the creation and enforcement of redundant policies and procedures.

    • Multilingual support- To reach the world wide audience an organization requires localization support for a number of languages and the ability to adapt to different time zones.

    • Service Oriented Architecture (SOA)- The ECM System’s ability to integrate with various types of systems is essential to ensure that your content is readily available across the enterprise.

  6. Strength of Vendor

    You ECM system provider should have the commitment, longevity and the financial strength to be your business partner for years to come. While evaluation a suitable vendor, you should consider:

    • The available educational and training materials
    • Training personnel
    • Availability of global tech support.
    • Ability of address issues in a timely manner.
    • Availability of other implementation partners and subject matter experts globally.

Conclusion

Whether you are considering an upgrade to your current ECM System, a replacement of an older system or the purchase of a completely new ECM System, there are many important criteria involved in electing the best content management system suited for your organization. Apart from the 6 points mentioned here there might be other requirements which will build your list further. We hope you find this useful and consider Valuebound to build your future. More information on our work is available at Valuebound.

Valuebound sponsoring BAD Camp 2016

BADCamp is a Drupal conference for the people. It’s an annual celebration of open-source software in Berkeley CA. We at Valuebound, are thrilled to be sponsoring BADCamp this year, to be held on October 20-23. We are excited to welcome more people be a part of BADCamp inspiring sessions and community!

 

Badcamp VB

How to Create Custom field in Drupal 8 (Part -1)

In a recent project we had to create a section that is having range  with the select list for the unit. It had to be usable in different sections of the layout and work the same. For this we came up with a pretty nifty (we think) solution of creating a custom field that solved this particular problem for us. I will walk you through how to create a custom field/widget/formatter for Drupal 8. There are Drupal console commands for generating boilerplate code for this…

To Create Custom field we need to create 

  1. Field Type
  2. Field Widget
  3. Field Formatter


This is the folder structure for creating the same

Temperature Range

  • temperature_range.info.yml
  • src/
    • Plugin/
      • Field/
        • FieldType/
          • TemperatureRangeItem.php
        • FieldFormatter/
          • TemperatureRangeFormatter.php
        • FieldWidget
          • TemperatureRangeWidget.php

Field Type creation
First, we need to create our own custom module, we can use drupal console for creating new module, then 

The namespace of that class should be \Drupal\MODULE_NAME\Plugin\Field\FieldType
In our example \Drupal\temperature_range\Plugin\Field\FieldType\BazItem

To create a field type, you need a class with the FieldType annotation.

The annotation above the class, within the doc comment, should include a unique id, and a label.

Then provide a schema for the field. This will be the properties that we have created above.

Then provide the field item’s properties and this will be the properties which we created

In the forthcoming blog, we will see how to create field widget and field formatter which both will complete the custom field creation

Get your Drupal8 Development platform ready with Drush8!

As we all know, we need Drush8 for our Drupal8 development platform. I have tried installing Drush 8 using composer, but sometimes it turns out to be a disaster, especially when you try to install Drush 8 on the Digital Ocean Droplet having Ubuntu 16.04.

I have faced the same issue in the last few months to get the Drupal8 development platform ready with Drush8. So I have decided to find a solution to fix that forever. Well, finally found one which are the following lines of commands.

cd  ~
php -r "readfile('http://files.drush.org/drush.phar');" > drush
chmod +x drush
sudo mv drush /usr/bin
drush init

If you are still facing any issue, please leave a comment, We will help you out to get your platform ready with Drush8.

When should your Digital Transformation journey include a Multilingual Website?

When you have a media website with visitors from a language background other than your default, it’s best to switch to a multilingual website to ensure you do not lose your business and have a continuous growth.   

Do you have website visitors from non-English speaking countries?

Do you know there are more than 40 Million native Spanish speakers in the USA out of which 72% prefer websites in their native language?  Then there is Chinese, French and so on to name some of the most popular language based users which add up to 75% with English being only one-fourth. What are you doing to target these 75%? Why not zoom in on the less focused and make loyal customers out of them? To them, you are not just another digital media company delivering the same old content from places they don’t relate to, to them you are more of their national daily.

How do you cater to your web visitors if they are non-English Speaking users?

Do you display the content in the same default language? You might have translated the content but then there is page layout, word spacing and expansion and contraction per language requires you to have a site which can handle such flexibility

Are you equipped to make changes for every new language that you add to your list?

Adding a new language to your website comes with challenges. Are you looking for answers that handle the complexity of language translation requirements? Are you thinking how to organize your content? You have blogs, headlines which link other articles together, out of that what all can be translated and shown to the users? All of it or only the basic content?

Will it affect to have an interface that speaks the language of your target market?

Of course, your website does not target people of one language. And having a monolingual website gives you a limited audience, which is a loss for your business. Hence it is about time for you to customize your website to accommodate new languages

What factors are keeping you from growing your business?

One aspect of getting feedback or suggestions is through forms. Forms are a critical part of your website through which users can connect with you, having a form page that displays only in one language is going to hamper business for you. It is, therefore, important that the forms are easy to use and presented in the user's’ native language.

With the boom of devices and screens available to consumers, people now have unhindered access to every content they want, the way they want, with a special focus on their favorite brands and sites. This sets the standard higher and creates a necessity for the brands to deliver the best of experiences — with no regards whatsoever to the device, size, screen, mobility or any other point of contact, here the experience matters because your customer’s expectation is high. As a matter of fact, the standard keeps getting higher and higher that it because some of the brands like yours have been setting an example for the others to follow.

Why do you need Multilingualism?

With the internet crossing the 10k day this past week, from the time it was invented the world of publication likewise has undergone drastic changes, we swipe our finger to turn the next page of a book and scroll the site to take a look at the news headlines. It is no more limited to one part of the world and people from all regions and languages have access to what you write.

Writing is digitally accessible and digitally published. Businesses are gearing up to reach and penetrate through every corner of the world and here is where localization comes into the picture. Your diversified and multilingual global society has immensely added to the importance of translation in the publishing industry. Media and publication industry needs to reach out to various geographical regions having its own distinct language.

The world of media and publishing witness rapid changes and is regularly making way for a broader audience. Most multinational media companies are already on the path of this transition to secure an international foothold. Whether you choose to go down this path now or later is the only question.

The team at Valuebound has experience of working on high-traffic multilingual Drupal websites. If you are still wondering if Multilingual is the right way to go, we can help you make this decision.

References -

Batch Process in Drupal 8

Batch process is the process of execution of a program in a series without interference of external source manually. In a Batch process, inputs are taken in batches or slots. However, now this has become more irrelevant with the term batch and essentially means to run a process or a job without an end user’s interaction. In Drupal, batch process will help to execute a similar programme.

In this tutorial, we will go through how to create a drupal batch process.

 

For the process we need a controller or a form from which we can trigger the batch process. In our case we will create a batch process to delete all Node. 

So let’s create a small module for that.

Drupal module development

Module Setup:

batch_example.info.yml

Let’s create routing.yml

batch_example.routing.yml

src/Form/DeleteNodeForm.php

Here in the form we just need a submit button to handle the request.

Here in the submission handler where we have defined the batch. 

$batch is an array of steps to be performed in batch process. In this batch we have two steps,

  • deleteNodeExample : In this method we will be handling deletion of node.
  • deleteNodeExampleFinishedCallback: This is the finish call back it will be called once deletion of all node is done. It will give the status message of the process.
  • Batch_set : Drupal batch_set method will execute set of operations in made in batches, so as to not interrupt processing.  

Now we need to define these methods, So will create a class say “DeleteNode” inside src directory.

 

src/DeleteNode.php

This was all about creating batch process in Drupal 8. For testing the batch we can use drupal Devel module to create dummy content.



Advance Your Business: Drupal 8 Support Ends - Take Action!

 

Convert your favorite HTML5 Bootstrap Template to Drupal 8 Theme!

Quite a few times we come across Bootstrap themes when we wish to use in our Drupal website. You have searched Drupal download and it is not available as sub-theme. How about creating a new theme in Drupal 8 out of HTML template. In this post we are going to discuss, how we need to approach and build Drupal 8 bootstrap sub theme based on a html bootstrap template.

Bootstrap is html, css and js framework for building mobile first responsive themes. Bootstrap is available for Drupal 7 and 8 with starter kits using cdn and less. If you need to build your Drupal 8 theme using bootstrap starter kit, please go through this simple tutorial on How-to-build-your-drupal-8-theme-using-bootstrap-less. We have explained the basic folder structure of Drupal 8 theme in one of previous blog post - understanding-of-drupal-8-theming.

We will be creating Drupal theme out of this in following steps -

Creating sub theme

First we need to download the base theme bootstrap and place it in `/themes` directory in web root. Create new directory for sub theme, let say `my_sub_theme`. For sub theme, to be usable minimum we need is theme info.yml file. Info file would be like this initially,

Theme based on HTML bootstrap template

Step one: Identifying regions

First step in theming based on html bootstrap template is to find out possible regions in context of Drupal 8 site. List of region in Drupal site can be obtained from `admin/structure/block/demo/my_sub_theme`. For bootstrap, it will be like,

File: my_sub_theme.info.yml
Code:
name: my_sub_theme
type: theme
base theme: bootstrap
description: 'A simple starter theme for Drupal 8.'
core: '8.x'

Once info.yml file is been defined, we can enable the new theme. At this point if you view the page, what you would see is nothing simple and default bootstrap’s look and feel. Now the next part would be how can we integrate our html bootstrap template.

Bootstrap theme regions

Once you found out the possible regions and the regions provided by bootstrap is more than enough you can skip this section. If you need to alter regions, list them in info.yml file. Then only listing regions would be available for newly created theme.

File: my_sub_theme.info.yml
Code:
name: my_sub_theme
. .
. .
core: '8.x'

regions:
  header: 'Top Bar'
  help: 'Help'
  content: 'Content'
  footer: 'Footer'

Step two: Create libraries.yml

Make a list of css and js libraries is been used in all page template. Also figure out list of css and js libraries used only in some pages (says only pages which having forms). Once this listing is been done, we are ready to create libraries.yml file. Libraries need to be defined section wise, like libraries needed for all pages as one section and libraries needed for specific set of pages as separate section for each. Suppose let libraries.yml be

File: my_sub_theme.libraries.yml
Code:
theme: # Libraries needed in all pages.
  css:
    theme:
      css/font-awesome.min.css: {}
      css/animate.css: {}
      css/style.css: {}
      # External library
      http://fonts.googleapis.com/css?family=Lobster: { type: external }
  js: 
    js/jquery.appear.js: {}
    js/jqBootstrapValidation.js: {}
    js/modernizr.custom.js: {}
    js/script.js: {}
  dependencies:
    - bootstrap/theme
contact_me: # Libraries needed only in contact page.
  js:
    js/contact_me.js: {}

In this libraries.yml file you might have noticed, basic bootstrap css and js libraries are missing. Since my_sub_theme is sub theme of bootstrap, we can specify what all libraries needed from base theme as dependencies. In above code, we have given `bootstrap/theme` as dependency where first part (bootstrap) is theme name and second part (theme) is key of library defined in bootstrap.libraries.yml.

Done with defining libraries.yml. Now how do we use it or include it or attach it? Just include in info.yml. Same way you can include any other libraries you need in info.yml.

File: my_sub_theme.info.yml
Code:
name: my_sub_theme
. .
. .
core: '8.x'

regions:
. .
. .

libraries:
  - 'my_sub_theme/theme'

# List of css need to removed.
stylesheets-remove:
  - themes/bootstrap/css/3.3.5/overrides.min.css

Libraries specified in info.yml will be attached for all pages. We may need some libraries defined in libraries.yml need to be conditionally or for specific pages. This can be achieved by using template_preprocess_HOOK() in my_sub_theme.theme file.

File: my_sub_theme.theme
Code:
function my_sub_theme_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    $variables['#attached']['library'][] = 'my_sub_theme/contact_me';
  }
}

For more info, you can refer Drupal 8 documentation Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module on how to achieve it.

We can avoid or remove some css from base theme to be get attached using `stylesheets-remove`.

Step three: Modifying template

Modifying html to suit the HTML bootstrap template will be more difficult task initially, but i must say you will enjoy it and find it challenging to work in Drupal 8 after turning on twig debugging. For turning on twig debugging, rename the file `sites/default/default.services.yml` to `sites/default/services.yml` and change the value of debug from false to true under section `twig.config` and finally clear the cache.

Drupal services yml

Now onwards, you can get template info and template suggestions from browser developer tool. It looks like

Debug twig template

So where ever we need to change the html structure, we can identify the template file and can override by simply copy pasting the file within our theme template directory. For example if we need to alter the /page.html.twig then we need to place this in `/themes/my_sub_theme/templates/system/page.html.twig`.

Also we can make use of theme suggestions to override template only for specific page or region or block. For example, if we need to alter html template of navigation region then need to copy `/themes/bootstrap/templates/system/region.html.twig` to `/themes/my_sub_theme/templates/system/` and rename it as `region--navigation.html.twig` as per theme template suggestions.

In Drupal 8, twig template engine is being used as default template engine. That’s why template file follows the extension *.html.twig.

New to twig template then, these basics of twig will help you

Set and Print variables

Use set tag with in {% ... %} for assigning values. While printing variables can be modified using various filters followed by pipe( | ).

{% set foo = ‘bar’ %}
{{ foo }} {# outputs ‘bar’ #}
{{ foo|title }} {# outputs ‘Bar’ #}

{% set foo = {‘bar’: ‘foo’} %}
{{ foo.bar }} {# outputs ‘foo’ #}
{{ foo[‘bar’] }} {# outputs ‘foo’ #}

Control statements

Like variable assignment, control statements like if, elseif, else and for loops should be contained in {% … %} blocks.

{% if menus|length > 0 %}
  • {% for menu in menus %}
  • {{ menu.link }}
  • {% endfor %}

{% else %}

  • {{ login_menu.link }}

{% endif %}

Comments

Commenting can be done using {# … #} blocks.

{# Inline comment. #}
{# Multi line commenting.
    {% set foo = {‘bar’: ‘foo’} %}
    {{ foo.bar }}
#}

Debugging variables

For dumping any variable use dump() function.

{{ dump(foo) }}

For more reference on twig, please go through Twig for Template Designers.

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