How to Sync Blocks Between different environments in a Drupal 8 website

A custom block is made of two entities, one for the placement and one for the actual content. Only the actual placement can be exported with cim. The content can not. Therefore this will result in "Block description Broken/Missing" error on site where the config is imported. And since there is no option to disable custom blocks from being exported through Configuration management, this will break the functionality.

Steps to reproduce

On Site A:

Create custom block

Assign this custom block to any region

Export configuration of the site

On Site B:

Import configuration from site A

Go to Block layout and you will see custom block in correctly assigned region, however block won't work or actually show anything.

Edit that block, you will see this messages:

Block description Broken/Missing

   This block is broken or missing. You may be missing content or you might need to enable the original module.

Go under Custom block library and you won't see custom block.

Block layout got exported but block content didn't resulting in broken relationship.

Block In Local Instance

In the above image a drupal block named “Block Content test” is added in content region in a local instance.

Block In Dev Instance

The above image shows that the block is missing after importing configuration using Drush command “drush cim”.

Way 1: Using Database Sync

  1. Create Custom Block in Site B.

  2. Replace db of Site A with Site B using drush sql-sync

  3. Now the block is available in Site A. So will place it in a region.

  4. Use drush cex to export config and commit to Site B.

  5. Use drush cim in Site B and the block will be placed in the region.

Way 2: Use Drupal drush functions to export config and hook_update_n & block uuid to update content.

  1. Create block B4 Test in Site A.

  2. Place the block in some region.

  3. Export using drush cex.

  4. Commit and run drush cim in site B

  5. Block error will be shown in Site B

  6. Write hook_update_n and  commit. Take Update in Site B and run update.php in Site B to add the block.

  7. Check Site B if the block is placed or not.

We have used Drush Commands “drush cex” to export block configurations and “drush cim” to import the configurations.

So Once drush cim is done in site B write a hook_update_N in your custom module's .install file use the block uuid to update the database of Site B.

After running update.php the block will be placed in the region

The first method can be used where the database size is less as it will take less time to sync the database. The 2nd method can be used where the database size is huge.

Reference: https://www.drupal.org/node/2756331


Depending on the scenario we can use any one of the methods. In this blog I have explained the two methods which we can use for updating blocks from one environment to another.

How to build a simple form using AJAX in Drupal 8

Ajax is a script on the client side communicating asynchronously with the server without a complete page refresh.The best description I came across about Ajax as “the method of exchanging data with a server, and updating parts of a web page – without reloading the entire page.”

In our project, while creating a new account if we give the existing username, on submitting the page it will throw an error. But, instead of reloading the page, we can just update certain parts of DOM. This can be achieved using AJAX. So, here is the example how to implement this ajax in drupal 8 forms.

In order to build a simple form using AJAX in Drupal 8 , we created a form with Username field. Using ajax we are going to validate that field. To achieve this, create a custom module ajax_example it requires 3 files which are ajax_example.info.yml, ajax_example.routing.yml, src\Form\AjaxExampleForm.php. The steps were listed below, how to validate the text field using AJAX.

Step 1: Create .info.yml

Let's create a yml file. A yml file is a file that specifies the configuration for a file i.e., to store metadata information about the project

Step 2: Creating .routing.yml Let’s create a .routing.yml called ajax_example.routing.yml. Each route is defined as a machine name in the form of module_name.route_name

Step 3: Create AjaxExampleForm.php

Create a new file called AjaxExampleForm.php inside of src/Form/{AjaxExampleForm.php}.

getFormId() function is used to create a unique id to the form.

buildForm() function is used to create the form and it has a textfield to validate the username using #ajax. Drupal provides the property ‘#ajax’ to a form element in your form array, to trigger an Ajax response.

checkUserEmailValidation() is the callback function to handle the server side of the ajax event i.e., to check the user or email is already exists in the database or not.

Drupal provides user_load_by_name() function for getting the username and user_load_by_mail() function for getting the Email. To return commands, you need to set up an object of class Drupal\Core\Ajax\AjaxResponse and the addCommand method is used to add the individual command to it.

Step 4: Here is our Ajax output in drupal 8 Form. The main objective of this blog is to validate the existing username or email without reloading the page.

Ajax output in drupal 8 Form

In drupal 8, we can achieve this by using ‘#ajax’ attribute and return the ajax response using the object of the class Drupal\Core\Ajax\AjaxResponse and added the individual command using addCommand method with the object of the class Drupal\Core\Ajax\HtmlCommand to show the message.

So, in this article, we have see an example regarding AJAX, to just update certain part of DOM, instead of reloading the whole page.

How to use Configuration Split Module to Split Configurations in Drupal 8

The configuration Split module allows users to define sets of configuration that will get exported to separate directories when exporting and get merged together when importing.

  • Drupal split module depends on Config Filter for the integration with the import/export pipeline of the Drupal UI and drush.

  • It is possible to define in settings.php which of these sets should be active and considered for the export and import

                                Here are a few things that are considered configuration:

Configuration split exposes a configuration entity which controls what you want to split off. Currently, you can

 

  • Blacklist modules: Any configuration that this drupal split module owns will automatically be blacklisted too.
  • Blacklist configuration: settings or configuration entities. These will be removed from the activesync directory.
  1.  Download and Enable Drupal configuration split module :- drush en config_split -y
  2.  Go to configuration  -> Configuration Split settings

Configuration Split Setting

  • Click on 'Add configuration split'. Naming is important, so we'll enter 'Dev split' as the name for this configuration. We'll also create a directory called 'sync-dev-split'. (where the config file will go from activesync directory)
  • Select Module’s from which configuration file (yml files ) will get split into another folder in root directory of your module .

Configuration Split Setting

  • There is an status Option which should be active (Checked)
  • Save

3. Doing exports and imports on dev or live .

From now on, if you want to import new settings whether it's on your dev or live environment, you can not use the drush core commands anymore. Use following commands: Go to Terminal 

A) Export your configuration in other folder

  • drush csex dev_split
  • sync-dev-split
  • Y/N option will be there =>Y
  • List of yml files => ls sync-dev-split
  • # to export on your dev environment ->    @dev:/home/drupal/drupal-core$ drush csex dev_split
  • # to export on your live environment ->     @live:/home/drupal/drupal-core$ drush csex live_split

B) Import Your configuration

  • In local -> drush csim dev_split
  • In dev site - drush @pantheon.config-split.dev csim dev_split
  • # to import on your dev environment ->    @dev:/home/drupal/drupal-core$ drush csim dev_split
  • # to import on your live environment ->    @live:/home/drupal/drupal-core$ drush csim live_split

                                                                                    OR

C) You can directly Import your Configuration

Go to Configuration-> Configuration Synchronization - If you have added multiple split config settings, then it will be shown like this in Configuration Synchronization

Synchronize Configuration Setting

There you can see Multiple Split configuration option like dev split & live Split

If you want to use “Dev split” go to your settings.php file

  • $config['config_split.config_split.dev_split']['status']= TRUE;
  • $config['config_split.config_split.live_split']['status']= False;
  • $config['config_split.config_split.test_split']['status']= False;

Result :

Synchronize Configuration Setting

References :

How to Create Configurable Block programmatically In Drupal 8

Blocks are the boxes of content that can be displayed in regions like sidebar first, sidebar second, content. This functionality is provided by the Block module in drupal 8. Here describing to creating Configurable Block programmatically in drupal 8 by using the drupal console.

Configurable Block module & skeleton files created by following drupal console commands:

$drupal generate: module

Generate_Module

By using drupal console to generate configurable block module it create configure_block.info.yml file like,

structure_info_file

Configure_block.info.yml file contain the following information:

info.yml_file
The .info.yml file contains metadata about the project like the name of the project (configure_block), type (module), description (This is an example of configurable block programmatically in drupal 8), core (8.x), packages (Custom) and dependencies etc.

 

Next, we need to create a plugin for Block Module. Create folder Plugin under src, create Block folder under Plugin then create DefaultBlock.php file under Block folder.

  • The path should be /src/Plugin/Block/DefaultBlock.php

(or)

Next, we need to generate Block module using following drupal console command,

 

$drupal generate:plugin:block

generate_plugin_block

After generated configurable block module by using drupal console, it should be like,

 

structure_plugin_block

 

The Configurable block module Skeleton in drupal 8 is like this:

  • module/custom/configure_block/src/Plugin/Block/DefaultBlock.php
  • module/custom/configure_block/configure_block.info.yml

where configure_block is a module name for our custom configurable block. The plugin of configurable block module file will have following code where we are defining our configurable fields in drupal 8.

 

DefaultBlock.php:

 

Here we take three fields of the configurable block which are hello_block_name, mobile_number and address. The message is to be displayed, based on what you enter in those fields of block module in drupal 8.

 

Next, install your configurable block module in drupal 8.

 

Goto

Extend >select install module>select your module name>click install.

install_block

 

Next place the configurable Block module in any regions are presented in drupal 8.

 

Goto

      Structure>Block Layout>click place block icon>select your block name>select region>save block.

Goto

    Configuration block>enter in the following field what you need to display output.

 

Configure_Block

Then go to the main page,

 

Configurable block Module displayed in some region (selected region example: sidebar second). It shows following output.

 

final_output

 

I hope this was helpful in getting you started with Custom configurable block in Drupal 8.


Reference: https://github.com/munavlakshmi/create-configure-block-in-drupal-8

Why Profiling is necessary for Performance Benchmarking?

40% of users abandon a website that takes more than 3 seconds to load.

Websites are typically viewed on a large variety of devices with various systems, it may be handheld device or desktops, might run a Mac OS or have Windows but the bottom line is when a visitor is on the homepage of your website or loading items on the e commerce portal or using some other functionality on the website they expect it to be fast and move with the speed of their finger swaps.

What affects Website Performance?

Performance of a website depends on a lot of factors, the performance of the code, factors that have been kept in mind while making that code, number of visitors currently viewing the website, connections to database and so on. To ensure smooth functioning of a website according to expectations it is necessary that it goes through performance testing.

Performance Testing gives the power to analyze your code and find bottlenecks and determine which parts of your code needs a tweak to boost the speed. It helps to determine the points of breakage of the technology stack used in the development of the application. It also helps to find the limit to the number of users the website can handle in case of a spike, like media and publishing websites when Presidential Elections were running.

How does performance boosting help?

  1. Wal-Mart trailed its competitors online until they made improvements. For every 1 second of improvement to load time, the site experienced up to a 2% improvement in conversion rate.

  2. Intuit cut load time in half and saw an increase of 14% in conversions.

  3. GQ decreased its average load time from 7 to 2 seconds and saw an 83% increase in traffic.

Source

You might have added some new functionalities to your website and now the server load has increased and also the memory usage and also the page is slow to load. But does that mean you change the hardware? Even if that is an option it is not a viable solution and this is exactly where performance profiling comes into the picture, to analyse and understand what makes the system slower and fix them.

Performance profiling is to investigate and analyse a code’s runtime behavior to understand the areas that need improvement and how to optimize a program’s performance. The data collected during the execution of a program helps developers to analyze the code.

It helps apps run faster, at different stages of deployment, Performance Testing helps to determine which particular feature addition to your web application has made it slower or analyse the behavior of apps.

How do Profilers work?

Developers say that different profilers work in different ways, however in general profilers examine programs during the runtime to find which assembly instruction is currently being executed (the program counter) and which routines called the current function (the call stack). This kind of sampling profiler can work with standard binaries, but are more useful if you have debugging symbols to work out lines of code given addresses in the program.

As well as sampling regularly, you can also use processor performance counters to sample after a certain number of events such as cache misses, which will help you see which parts of your program are slowing down due to memory accesses.

Other profilers involve recompiling the program to insert instructions (known as instrumentation) to count how often each continuous set of instructions (basic blocks) are executed, or maybe even record the sequence in which basic blocks are executed, or record the content of variables at certain places.

The instrumentation approach can give you all the precision and data you might want, but will slow down the program and that will change its performance characteristics. By contrast, with sampling based approaches you can tune the performance impact against the length of time you need to run the program against the accuracy of the profile data you obtain.

Why Profiling for Performance Benchmarking is necessary ?

Performance profiling is pivotal to the performance of the website it helps to understand the client-server response time. Performance issues during a spike or in peak times. It helps to understand if any database connections or the technology is a holdup in your web application and help change any components causing so. It also determines behavioral changes in applications caused with a new release.

Performance profiling works as a benchmark against coding changes and efficiency  of the website.

How to Migrate a Website to Drupal 8

We all know that now is the time to move into Drupal 8 from the other Drupal versions.  And it is very important for a Drupal developer to know about Migrating into Drupal 8 and Website Migration in general. This was a session presented at the DrupalCamp Mumbai 2017, I spoke about the experience of migrating a Legacy System which built on Adobe ColdFusion.

Website migrations occur now and then for numerous reasons and now that we are working on Drupal 8, it is absolutely necessary to migrate from Drupal 6 or 7 to Drupal 8 to fully utilize the power of Drupal.

The session focuses on:

  • Case Study of  Migrating a Legacy System into Drupal8.

  • Migration in Drupal 8 Core.

  • D6 to D8 migration.

  • D7 to D8 migration.

  • Migrating from JSON and CSV data.

  • Migrate Source Plugin

    • Why or When we need to write Migrate Source plugin?

    • How to Write Migrate source plugin?

  • Migrate Process Plugin

    • Why or When we need to write Migrate Process plugin?

    • How to Write Migrate Process plugin?

  • Migration using Drush.

 

Related:

Why & How to Migrate Drupal 8

Porting drupal 7 module to drupal 8 using Drupal Module Upgrader

How to migrate Users from a CSV file in Drupal 8?

 

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

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