How To Create Custom SOLR Search With Autocomplete In Drupal 7

In many cases, users visiting a site already know what they are looking for, hence they  head straight to the search box. Since it is likely to be their first point of contact with the website, retailers must ensure that they get it right the first time. This is to avoid the issue of users getting frustrated by inaccurate or badly-ranked results and as a result moving on to a different site.

A good starting point is to introduce a ‘suggest’(Autocomplete) function, which lists a drop-down menu of various  search queries containing the text fragment they have typed.

We will integrate the apache solr with our drupal site and make autocomplete search.
For this, we need to query the apache solr and then get the results from the apache finally  displaying it in autocomplete. With this we can customize our autocomplete search result.

Modules Required

  • Apache solr search
  • Apache solr Autocomplete

To Install and configure apache solr with drupal 7 please follow this

http://valuebound.com/resources/blog/installing-configuring-apache-solr-520-with-drupal-7-using-search-api-ubuntu-1404
 

Step 1:
Create the block to place search text field

/**
 * Implements hook_block_info().
 */
function solr_search_block_info() {
  $blocks = array();
  $blocks['solr_search_block'] = array(
    'info' => t('Place the Solr Search Block in any region'),
  );
 
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function solr_search_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'solr_search_block':
      $block['subject'] = '';
      $block['content'] = drupal_get_form('solr_search_block_form');
      break;
  }
  return $block;
}

Step 2:
Create the custom form with text field and make the text field autocomplete. Then place the following form in the block

 function solr_search_block_form($form, &$form_state) {
$form[‘search’] = array(
        '#type' => 'textfield',
        '#id' => 'edit-custom-search-block-id',
        '#autocomplete_path' => 'solr-search/autocomplete',
        '#attributes' => array('placeholder' => t('Search any thing'), 'class' => array("edit-custom-search-block"))
      );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Search',
  );
return $form;
}


/*
 * Implementing hook_menu()
 */
function solr_search_menu() {
  $items = array();

  $items['solr-search/autocomplete'] = array(
    'page callback' => 'search_autocomplete',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );
  return $items;
}

Step 3:

Let’s look at the callback function of the hook_menu which returns the autocomplete result.

function search_autocomplete($keyword = '') {
  global $base_url;
 
  $search_spell = _get_search_label_spellcheck($keyword);

  if (isset($search_spell) && !empty($search_spell)) {
    //$search_spell_link = l(t($search_spell), $base_url.'/search/site/'.$search_spell);
    $search_spell_link = l(t($search_spell), $base_url . '/search/site/' . $search_spell, array('attributes' => array('class' => array('search-custom-spellcheck')), 'html' => TRUE));
  }

  /**
 * Helper function that suggests ways to complete partial words.
 *
 * For example, if $keys = "learn", this might return suggestions like:
 *    learn, learning, learner, learnability.
 * The suggested terms are returned in order of frequency (most frequent first).
 *
   */


  $suggestions = array();
  $suggestions = array_merge($suggestions, apachesolr_autocomplete_suggest_word_completion($keyword, 5));
  if (apachesolr_autocomplete_variable_get_suggest_keywords() || apachesolr_autocomplete_variable_get_suggest_spellcheck()) {
    $suggestions = array_merge($suggestions, apachesolr_autocomplete_suggest_additional_term($keyword, 5));
  }
  if ($suggestions) {
    foreach ($suggestions as $key => $suggestion) {
      $spell = substr($key, 1);
      $search = _get_search_complete_keywords($spell);
      if (!empty($search)) {
        foreach ($search->response->docs as $sugg) {
          $node_id = $sugg->entity_id;
            if (!empty($node_id)) {
              $node_detail = node_load($node_id);
              $title = $node_detail->title;
              $matches[$title] = _get_search_autocomplete_list_display($sugg, $title);
            }
        }
      }
    }
  }

  if (!empty($matches)) {
    $url = $_GET['q'];
    $url_explode = explode('/', $url);
    $url_last = end($url_explode);
    //    $matches['more'] = l('VIEW ALL PRODUCTS', "$base_url/search/site/$url_last", array('attributes' => array('class' => array('search-more-autocomplete'))));
  }
  else {
    if (!empty($search_spell_link)) {
      $spellcheck_html = '

Finding for"' . $search_spell_link . '"?
';
      $matches[$keyword] = $spellcheck_html;
    }
    $matches[""] = "NO RESULT FOUND";
  }
  drupal_json_output($matches);
}


function _get_search_label_spellcheck($keys) {
  if ($keys) {
    $keys = preg_replace('/[^A-Za-z\-]/', '', $keys);
// Ask Solr to return facets from the 'spell' field to use as suggestions.
    $params = apachesolr_autocomplete_basic_params($suggestions_to_return);
    if (!empty($keys)) {
 //Helper function to get suggestions from Solr.
      $result = apachesolr_autocomplete_suggest($keys, $params, $keys);
    }
    if (!empty($result) && isset($result['response']->spellcheck)) {
      foreach ($result['response']->spellcheck->suggestions as $key => $check) {
        $spell[$key] = $check->suggestion[0];
      }
    };
    return $spell[$key];
  }
}

Step 4:
Next, we need to query the apache solr based on the text entered in the text field. This  will return the result from the solr.

function _get_search_complete_keywords($keyword) {
  if (!empty($keyword)) {
    $solr = apachesolr_get_solr();
    $query = apachesolr_drupal_query("custom", array('q' => $keyword));
    $query->addParam('rows', '1000'); // How many rows of result to display default it is 10.
    $query->addParam('qf', 'label'); // Only search in title
    //The bundle which you want to search
    $query->addFilter("bundle", "article");
    $query->setSolrsort('sort_label', 'asc');
    $resp_search = $query->search();
    return $resp_search;
  }
}

Step 5:
To display the autocomplete results in the textbox enter the following code:

function _get_search_autocomplete_list_display($sugg, $title) {
  global $base_url;
  if (!empty($sugg)) {
    $nid = $sugg->entity_id;
  }
  $n_link = $base_url . '/node/' . $nid;
  $title_link = l(t($title), $n_link, array('attributes' => array('class' => array('search-title-autocomplete'), 'title' => $title)));
  $data = '

' . $title_link .
      '
';

  return $data;
}

There you go! Now with autocomplete search allowing you the opportunity to tweak your content which is present in the article content type more users will find the information they need on your site.

Profiling Drupal Performance with Webgrind and Xdebug

Xdebug Profiling is all about measuring the performance of PHP code.


Here we go!

Requirements:

  1. Xdebug, with profiler enabled
  2. Webgrind
  3. Xdebug Addon plugin for browser

1. Xdebug with profiler enabled

For setting up the environment, edit the php.ini file and add following lines.

xdebug.profiler_enable_trigger = 1

If you want the cachegrind in a prefered location, then add the following

xdebug.profiler_output_dir="/var/www/html/xdebug_profiler"

If you want a prefered name, add below line of code

xdebug.profiler_output_name="cachegrind.out.%u.%H_%R"

Once added, restart the web server in my case

service apache2 restart

Once you restart the server, visit the index page where you have PHPInfo with profiler enabled, as shown in the image.
 

profiler-settings


2. Webgrind
For installing the webgrind, download the latest version from the below url

https://code.google.com/archive/p/webgrind/downloads

Extract it and put in the root folder of your web server. When you hit the localhost you will be able to see the running webgrind. In my case I have the existing cache grinds

webgrind


3. Xdebug Addon plugin

Next we go to installing the xdebug plugin. First download and enable the plugin,

xdebug

Once done, you will be able to see the icons shown in the below image on your browser.

xdebug2

Enable the Xdebug trace as shown in the image.



Now let's check the performance.

To do this initially we write a test code in a testme.php We have 3 for loops in our case, which runs heavily when compared to the rest.The 3rd one will be slowest one in our case,So this should be shown by our webgrind

 testme0

 

Run the testme.php code by hitting the url with the parameter XDEBUG_PROFILE=on

testme1

Now visit the webgrind at you localhost and select the testme.php‘s cache grind.
You will be able to see the output as shown in image

testme3


As shown in the above image


In line 24 of testme.php the time consumed is 99.84 percent of you entire testme.php time execution.


So in Drupal case also hit the page url as shown below where we are hitting the node/4 with XDEBUG_PROFILE=on

drupaltest1


Visit the webgrind on localhost, where one more cache grind will be created for drupal one.
 

drupaltest2

Similarly as in the test.php case, we can see at which particular line the code is taking the more time.

 

Conclusion


In this manner we can check for the specific piece of code which is taking more time to execute and optimize that particular piece of code.

Additionally, you can see the hierarchy of all function calls and follow the same steps to check for the root function performance.

There you have it!

How to create Custom Rest Resources for POST methods in Drupal 8

One of the biggest changes in Drupal 8 is the integration of Rest services in the core. With use of Views it become very easy to create RESTful Services.

But there are certain situations when you need to create your own custom REST Resources. There are documentations available for creating a GET request using Views and using custom module. However there isn’t much documentation available for creating Rest Resources for POST methods.

In this article I will be sharing, how to create a REST Resource for POST methods. This Rest API will create an article in Drupal 8 site from an external application.

Note: I will be using Drupal Console for generating the module and code boilerplates.

Create the module
drupal generate:module

module

 

Create the Rest Resource Plugin
drupal generate:plugin:rest:resource

rest

 

The above command will create a Plugin for rest resource in your module. The url /api/custom is the url for your resource which can be accessed like localhost:8000/api/custom?_format=json

Enable the resource from RestUI
 

rest UI


This was the easiest part.  Now we need to modify the Plugin created by Drupal Console to get the Resource working for POST methods.

In the above file change the Annotation lines

*  uri_paths = { 
*    "canonical" = "//api/custom" 
*  }

To

*   uri_paths = {
*     "canonical" = "//api/custom”,
*     "drupal.org/link-relations/create" = "//api/custom"
*   }

Otherwise your API will be be expecting the request to use the /entity/{entity_type} endpoint, which will conflict with the endpoint provided by core.

Next we need a serializer class for normalising the data being passed.
Add serialization_class = "Drupal\node\Entity\Node", in the Annotation for the Resource.
This will ensure that the data being passed is of entity type Node.

To run the resource use a Rest Client for example Advanced Rest Client.

advanced Rest Client

Now to create the node from the Rest Client change the create() function in your Resource class.

All done! This, is how we can create a node using Rest Resource for POST methods in Drupal 8. Here is the complete code for the Resource Plugin file:

Boost your Drupal development with Docker

Vagrant is a great virtualisation tool, which I prefer heavily for my development purposes. But sometimes it gets a bit hectic and resource consuming, to set up a new vagrant environment to work trivial things or testing out a module/API. 

Not being a great fan of local *AMP stack I was looking for some alternative to Vagrant to use. In comes Docker, which is super fast and very easy to setup. Containers (“virtual machines”) are easy to destroy and  rebuild.They do not require the overhead of virtual machines but they  still provide a high level of isolation from the host OS.

Docker hub have many Docker containers for Drupal which are ready to use . But I prefered to create my own Docker container which just works and runs Drupal smoothly.

  1. Create a directory anywhere in your system. I have it placed in ~/Documents/docker/drupal. (“drupal” is my Drupal root folder)
  2. Create a file called Dockerfile and paste the below code:
  3. What it does? This will install all the necessary packages required for running Drupal. Note: There is no MySQL package installed.
  4. Once the Dockerfile is placed, create the Docker image out from your Dockerfile.
  5. Run docker build -t drupal . This will take a  few minutes, which will create an image named “drupal”.
  6. Now we need to have a container for MySQL. The reason for having a separate container for MySQL is to make my Drupal container faster.
  7. Run docker run -p 3308:3306 --name drupal-mysql -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=drupal -d mysql:5.5 This will again take few minutes to download the MySQL image. Once it’s downloaded, from next time the command will be executed in milliseconds. NOTE: You need to give the MySQL container IP as host and 3308 as MySQL Port.
  8. Run the Drupal container from the image created in Step 4.
  9. docker run --name drupal8 -p 8080:80 -p 8028:22 --link drupal-mysql:mysql -v ~/docker/drupal8/drupal:/var/www/html -d drupal This will forward the Apache port 80 of the host system to 8080 port for the container. Also notice we are mapping our MySQL Container to the Drupal container's MySQL.
     

That’s it. Now if you do a docker ps you will see the running docker containers.

Docker ps

Now, go to http://localhost:8080 and you will see the Drupal installation screen, from where it is plain Drupal installation.

Brownie Points:

  • When your work is done: docker stop drupal-mysql && docker stop drupal8
  • Start working again: docker start drupal-mysql && docker start drupal8
  • Destroy the environment and rebuild: 
    • docker rm drupal-mysql, then `docker run -p 3308:3306 --name drupal-mysql -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=drupal -d mysql:5.5`
    • docker rm drupal8, then  `docker run --name drupal8 -p 8080:80 -p 8028:22 -p 3038:3036 -v ~/docker/drupal8/drupal:/var/www/html -d drupal8`

How to define your own Services in Drupal 8

Service  is a PHP class with some code that provides a single specific functionality throughout the application. So you can easily access each service and use its functionality wherever you need it. Because of that it is easy to test and configure in your application. This is called service-oriented architecture which is not unique to Symfony or even PHP.  

The Services and Dependency Injection Container concepts have been adopted by Drupal from the Symfony framework.  Accessing the database, sending email, or translating user interface are examples for the services in Drupal 8. 

Lets look at how to define your own service in drupal 8 custom module Development?

 

Step 1:
Create the .info.yml file [custom_services_example.info.yml]

Step 2:
Create the ‘mymodulename.services.yml’ file [custom_services_example.services.yml]

Here the file name is ‘custom_services_example.services.yml’ where the ‘custom_services_example’ is our module name.

custom_services_example.say_hello’ is the service name defined by us, , Where we need to follow the pattern of ‘module_name’ concatenate with a ‘unique_name’.

We have the class name for services. ‘class: Drupal\custom_services_example\HelloServices’ which will be kept under the ‘src’ folder.

Also the dependency can be added the  following way 
arguments: ['@modulename.services1', '@modulename.services4', '@modulename.services7']  
In this case there are no  dependencies.

For the detailed explanation on  the structure of the .services.yml file please visit https://www.drupal.org/node/2194463

Step 3:
Create the class ‘HelloServices.php’ under the ‘src’ folder

This is simple class provide the service.

How to access the our own defined service?

Accessing the service globally. 

$service = \Drupal::service('custom_services_example.say_hello');

If you want to test this , you can enable the devel module and go to the path ‘devel/php’ and  run the following code 

 

$service = \Drupal::service('custom_services_example.say_hello');
dsm($service);
dsm($service->sayHello('rakesh'));

So you will get the following output.

 

  • Drupal\custom_services_example\HelloServices Object
    (   
          [say_something:protected] => Hello World!   
          [_serviceId] => custom_services_example.say_hello
    )
     
  • Hello rakesh!
     


https://github.com/rakeshjames/custom_services_example

For  more details please visit  the following links

  1. https://www.drupal.org/node/2133171
  2. http://symfony.com/doc/current/book/service_container.html
     

The Global Training Day, Bangalore

April 9 was a day filled with enthusiasm as we set forth with “The Drupal Global Day training” here at Valuebound. With a crowd of over 20 people and 5 trainers the knowledge sharing session was very fruitful.

The session started with an introductory note on Drupal to the diversified audience from different industries right from IT & ERP to Digital Marketing. Having gained the basics of Drupal, trainers encouraged the attendees to start with their first hands on experience of Drupal.  The participants were excited to create their own website without using a single line of code.

The session was filled with lot of queries & heated discussions making it an interactive conclave. Drupal Global Training Day turned out to be successful when a large part of the crowd showed interest in taking the session to the next level. Many were interested in being a part of the upcoming Drupal Camp, Bangalore in July’16.

Here are a few shares on the same.

How to build your Drupal 8 theme using Bootstrap & Less

Bootstrap is a true blessing for web developers which is a sleek, intuitive and powerful mobile first front-end framework for faster and easier web development. When you mix that with LESS pre-processor you get a mighty tool for creating a Drupal 8 theme.

In this tutorial we will be looking into initiating your own custom theme using Drupal’s Bootstrap base theme. The Drupal Bootstrap base theme bridges the gap between Drupal and Bootstrap framework. Drupal 8 being relatively new, has very little documentation available to use Bootstrap, which now has a stable release for Drupal 8.

To spare you some frustration and as a source of resource for our staff, I've arranged an orderly guide for making your own sub-theme.

  1. Download, extract and place the Bootstrap base theme in your “theme” folder. It doesn’t make any difference if the theme stays disabled as we will be using it just as a parent theme for our sub-theme. N.B. : Unlike Drupal 7, Bootstrap for Drupal 8 does not require jQuery Update module.
     
  2. Copy the entire less folder from “/themes/bootstrap/starterkits” and place it in “/themes” along with bootstrap directory.bling

     

  3. Rename the less folder as the name of your theme. Let’s say we call it “bling”less
     
  4. Rename the following files in your “bling” theme directory:
  • THEMENAME.libraries.yml to bling.libraries.yml (All the libraries associated with your theme will be entered in this file)
  • THEMENAME.starterkit.yml to bling.info.yml (The info file for your theme)
  • THEMENAME.theme to bling.theme (SImilar to template.php in Drupal 7)
  • config/install/THEMENAME.settings.yml to config/install/bling.settings.yml (This file is only used to override existing settings.)
  • config/schema/THEMENAME.schema.yml to config/schema/bling.schema.yml (Schema for the theme setting configuration file of your theme.)

5. Update your bling.info.yml

6. Download Bootstrap Source and upload it to “bling” folder. The source directory is named as bootstrap, which  contains the Source Less, JavaScript, and font files.

7. Next compile the less file which will create the style.css file. On compilation the style.css will be filled up all the Drupal specific overrides, Bootstrap CSS and also your custom css.
lessc less/style.less > css/style.css

8. Enable your theme from Drupal UI and you should see the base Bootstrap theme in action.

 

homepage

Brownie Points:

  • Add theme.js file:
    • Create a directory “js” in your theme
    • Add a file named theme.js which will hold the JavaScript applicable sitewide.
    • Add the library in the bling.libraries.yml as:
      js:
        js/theme.js: {}

 

  • Add a FontAwesome CDN for getting font icons:
    • Add this to bling.libraries.yml under css directive:
      'maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css': {type: external}

Your libraries file should look like this after adding these two items:

How to write the custom Drush Commands in Drupal 8?

Writing custom drush commands in Drupal 8 is not exactly like Drupal 7 but it is similar. Here also, we are implementing hook_drush_command().   

The only difference is in the file structure.  As we all know In Drupal 8 ‘.module’ file is not mandatory in the module root folder. Hence In Drupal 8 for creating custom drush commands, we only need two files.

  1. MyModuleName.info.yml
  2. MyModuleName.drush.inc

Where,description will be listed under Other commands: (custom_drush_command)

'description' => 'Echo the name you type with Say hello commandSay hello.'

drush_command

 

The command can be accessible in two ways by typing item_id say-hello' or using alias say:hello

drupal dependencies' => ['custom_drush_command'],
This tells to drupal that our drush command which has dependency, will work if we have our custom “custom_drush_command" installed.

 

In this way we can execute our custom new drush command using drush say:hello ‘your name’ or  drush say-hello ‘your name’

drush_command_execution

 

drush_alias_command_execution

 

How to enable and use:

  1. Install the module
  2. Open the terminal and ‘cd’  to your drupal root folder.
  3. drush cache-clear drush
  4. drush cr
  5. drush say:hello ‘your name’ or  drush say-hello ‘your name’


Source Code: https://github.com/rakeshjames/custom_drush_command

How to reduce the risk of your Drupal 8 application using Backup & Restore?

Imagine this! You are typing hundred lines of code, fixing bugs after bugs and finally after countless efforts the program successfully runs. Uff!! What a feel when you finally crack the code! But wait, what if in a blink of an eye everything vanishes off? What if, your site which was running properly suddenly stumbles a minute later?
Isn’t it any coder’s nightmare? You curse yourself for not taking backup. This article will save you from that dreadful situation.
 
Not only is creating and storing site backup a good practise, but it also ensures site stability and helps in further updation.
 
In order to backup a Drupal site you need to take care of code and database.

  • The first problem we came across is placing the Drupal directory trees under revision control.
  • The second one is about database which requires a more careful analysis.

     

Before we learn about how to use Backup & Migrate module along with Drush, let us cover some of the optimal strategies for backing up and restoring MySQL database.

General practices:
 

  1. Always backup the entire site before updating or upgrading.
     
  2. Date your backups. Save each file with a title that includes the date of the backup.
     
  3. Save a copy of backup in a different location other than your web server. Remember, if your web server crashes, you may lose your backup files too.
     
  4. Inquire about your ISP or web host's backup policies. Most good web hosts have a backup plan that kicks in every 24 hours.
     
  5. In addition to your web host's backups, routinely do it yourself. Periodically run a separate backup monthly, weekly, daily or whatever fits your site's needs.
     
  6. Restore your backups using the same method as you took the backup.
     

Why should I backup?
 

  1. If for some reason your website goes awry, sometimes restoring it from a recent backup is the only option available.
     
  2. New development environments can be created easily.
     
  3. Module upgradation and patches can be tested better when using a recent backup of your production site.

Tools available for Backup & Restore
If you are on Linux you can do Mysql Database Backup / Restore using below mysql and mysqldump command lines


Backup Local Database without password
mysqldump db_name > db_file.sql
 
Backup / Local / Remote Database With Password
mysqldump -u USERNAME -p dico db_name > db_file.sql
 
Backup A Table
mysqldump -uUSERNAME -p db_name tab_name > tab_file.sql
 
Backup and compress using gzip
mysqldump -uUSERNAME -p db_name  | gzip > db_file.sql.gz
 
Restore a Database
mysql -uUSERNAME -pPASSWORD db_name < db_name.sql
 
Restore a gzip compressed file using gunzip

gunzip < db_file.sql.gz | mysql -uUSERNAME -pPASSWORD db_name


Backup & Migrate:
This module facilitates emergency recovery and site migration. We can configure it for automatic backups saved to the file system - with more frequent backups during development. We can also create a manual backup. That way, you have a "restore point" in case of disaster.
 
While there may be some issues of security when you save the database and content as a file, the benefits of having a rollback in case of disaster are significant.
 
Drush
Drush is a command line shell and UNIX scripting interface for Drupal. Drush core ships with lots of useful commands for interacting with code like modules/themes/profiles. Similarly, it runs update.php, executes sql queries and DB migrations, and misc utilities like run cron or clear cache.
 
To use Drush you need to have shell (SSH) terminal access to your server and be able to install and configure the Drush utility code.

Step 1: Drupal has known problems in clearing some cache tables, that are left unaffected by the normal cache clearing in Drupal or Drush. Solve this by clearing expired cache elements manually by running Drush.
 
The most convenient way to rebuild Drupal's cache is by using Drush
RUN drush cache-rebuild
alias: drush cr
alias: drush rebuild

cache_clear


Step 2: Once you cleared the cache, the next step is running the backup command.
RUN: drush archive-dump

archive_dump



So, we can view our site dump is being downloaded to
/home/valuebound/drush-backups/archive-dump/20160217071827/drupal8.20160217_071828.tar.gz
This .tar file carry site & database dump.
 
If you would like to take just the sql dump,
RUN: drush sql-dump > ~/
This will create .sql file in your home directory.

sql_dump

 

Step 3: To Restore sql dump.
 
RUN: drush sql-cli < db_name.sql
Open a SQL command-line interface using Drupal's credentials.

data_restore


FTP
The File Transfer Protocol (FTP) is a standard network protocol used to transfer computer files between a client and server on a computer network.

FTP is built on client-server model architecture and uses separate control and data connections between the client and the server.

FTP

Where section a is local Directory
            section b is currently uploaded file location folder.
            section c is remote server folder list.
            section d is remote server file listing.
 
By pressing right key we can easily get the copy / download option for the particular folder.
 
Step 1:
Backup all the files and folders inside your Drupal directory. You can do that by downloading them via your favourite FTP client.
 
Step 2: Backup/Export your database. Then, you have to export your Drupal database. You can do that by using PHPMyAdmin.
 
Please, make sure that you choose the correct database, which your Drupal application uses. If you are unsure about the Drupal database name, you will be able to find it in the settings.php file.
 
Now you can sit back and relax as you have successfully backed up your data and you can restore it any time you want!

How to render blocks in twig files

After lot of research, finally got the way to render blocks in twig files.

Basically there are two type of renders.

  1. When there is an existing instance of the block in the layout. The the block can be rendered in twig using preprocess as
    $block = Block::load('mediablock');
      $variables['social_links'] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($block);
    
  2. There is no instance or configurations for the block. Then in the preprocessor we need to create the instance, build the block and then render it
    $block_manager = \Drupal::service('plugin.manager.block');
      $config = [];
      $plugin_block = $block_manager->createInstance('farmjournal_social_sharing', $config);
      $render = $plugin_block->build();
      $variables['farmjournal_social_sharing'] = render($render);
    
Download the Drupal Guide
Enter your email address to receive the guide.
get in touch