Tag: custom drupal module development

Features & Use Of Display Modes In Drupal 8

Display modes are one of the core functionalities of Drupal 8. They are easy to create and provides great flexibility in terms of theming at entity viewing and editing level. Display modes are available for content, comment, contact messages, custom blocks, taxonomy terms, users. They are also available to views adding more power to views.

Display modes are located at Admin -> Structure -> Display modes -> View mode.

Two types of display modes are available: “view modes” and “form modes.”  Both these are an example of configuration entities.

View modes allow site builder to request a field to be rendered in a certain way. For example, we can have an article that has doctors field has entity reference. An article full mode display, we can request few details of doctor to be displayed. We can create a new display mode (“Doctor details”) to do so. On Doctor’s full view, we can include a brief summary of articles associated with them.  (In detail: https://goo.gl/9J2oms)

To create View mode 

Navigate to Admin -> Structure -> Display modes -> View mode

  1. Click on “Add view mode” to add new view mode

  2. Created view mode is available on content types. Navigate to manage display of the content type and enable view mode.

    Manage display console test.png

Once enabled, this mode can be used on referenced field.

Once view modes are enabled, we can theme it as per requirements. To get template suggestions, you need to turn on debug property from services.yml.

You can find theme suggestion in inspect element.

Display modes can also be used based on conditions and we can switch mode based on conditions.

function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  // For nodes, change the view mode when it is teaser.
  if ($entity->getEntityTypeId() == 'node' && $view_mode == 'teaser') {
    $view_mode = 'my_custom_view_mode';
  }
}
Hope this helped you to understand Display Modes in Drupal 8, Feel free to drop us a line for any Drupal 8 related work/queries/tasks, or Need any assistance regarding Drupal 8 Web design & Development.
Always ready to help 🙂

Advertisements

Everything You Need To Know About Drupal Mail System

Drupal Mail System

This blog is all about Drupal Mail system. Email sending in Drupal is entirely straightforward. Essentially you just need to manage two stages to send an email to somebody:

In Drupal to sends an email we need to take care of two things:

  • Declare all the required properties (subject, body, headers, etc) under hook_mail().
  • Call drupal_mail() with the argument for actually sending the email.

However, in the situation like greater and complex site, the above strides won’t be sufficient. In any case, Drupal gives us the Flexibility to redo email sending process, before that it’s important to know how stuff functions in the background first, with the help of Drupal you can easily generate custom pdf using the print module. In this blog, I’ll demonstrate to you how you can redo and extend the Drupal mail framework to satisfy your necessities.

The Email Sending Process

While sending an email drupal_mail() function uses system class for sending an email. Each mail framework needs to actualize MailSystemInterface class to define its own mail sending conduct.

MailsystemInterface class utilizes two strategies:

  • format()
  • mail()

The Mail System Module

Mail related settings can be set through Configuration > System > Mail System.

The mail system variable contains two things:

  • default-system => DefaultMailSystem
  • mailsystem_theme => current.

These key-value pairs are the settings you can adjust under the “Mail System Settings” fieldset.

DefaultMailSystem

The default-system email key describes which mail system class will be used by default for all outgoing emails.

If you don’t modify the site-wide mail system class then this one will be used by drupal_mail() by default.

The mailsystem_theme defines which theme will be used to render emails. Let’s say you are using Mime Mail which

uses a specific template file for it’s emails. The Mail System module checks every theme registry entry for a specific

“mail theme” key/property and if it exists in a particular entry then the specified mailsystem_theme value will be used

to search for more specific template files when the theme registry entry related theme hook will be called.

New Class

If you have two or more different mail system classes available in your system provided by different modules.

If you want to use any custom mail class which would use format() method of one mail system class and mail()

method from another class, so here you can use New Class which allows combining two different mail system classes.

New Setting

The Mail System module permits you to effortlessly add new email keys to the mail_system variable by choosing a

module and a particular email key from its hook_mail() execution.

 

Afterward added new email key to the mail_system variable you will ready to choose mail system class for it.

You will have the capacity to see it under all inclusive default MailSystemInterface class settings.

At the point when drupal_mail is called with your demo_custom _mail email key, then the in a roundabout way utilized

drupal_mail_system() function checks if this email_key exists in mail_system variable. It finds the related key then the

related mail system class will be utilized rather than default class.

Hope this helped you to get most out of the system. Feel free to share your reviews and need assistance regarding

Drupal Development Services. #WeDrupalEveryday

Pick the best answer for your requirements.

Migrate Locations From Drupal 6 site to Drupal 8 site

Migrate locations from D6 to D8

Recently i had a problem where i need to migrate locations added by “Location” module in Drupal 6 site to Drupal 8 site. Currently “Location” module does not provide Drupal 8 version, so i used “Address” module in Drupal 8, but still i need to get all contents.

To solve this, i have created a custom module in Drupal 8. Steps to update locations:
  1. Create a folder /modules/custom/MODULENAME
  2. Create “MODULENAME.info.yml” file inside MODULENAME folder with following details:
           name: MODULE NAME (This can be anything you want)
           Description: MODULE DESCRIPTION
Package: Custom
           type: module
core: 8.x
           dependencies:
– address:address
           More info on creating modules .info.yml file can be found here.
      3. Now, as i need to migrate data on cron run, i created “MODULENAME.module” file and implemented hook_cron.
   <?php
/**
 * @file
 * File to migrate contents
 */

    function MODULENAME_cron() {
        Write code here…..
}
We need to connect to Drupal 6 database for exporting its content. Add the following code in /sites/default/settings.php along with the default database connection:
  $databases['external']['default'] = array (
  'database' => ‘DATABASENAME’,
  'username' => ‘USERNAME’,
  'password' => ‘PASSWORD’,
  'prefix' => '',
  'host' => 'localhost',
  'port' => ‘PORT’,
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);
We have used “External” for connecting to Drupal 6 database. “Default” is used for Drupal 8 database connection. So now there will be 2 database connections in settings.php
Code to switch to Drupal 6 database connection:
    // Switch to external database
\Drupal\Core\Database\Database::setActiveConnection('external');

// Get a connection going
$db = \Drupal\Core\Database\Database::getConnection();

Database Query to fetch locations from Drupal 6 database:

// Query to fetch all locations
  $query = $db->select('location', 'l');
  $query->join('location_instance', 'li', 'l.lid = li.lid');
  $query->fields('l', array('name', 'street', 'additional', 'city', 'province', 'postal_code', 'country', 'latitude', 'longitude'));
  $query->fields('li', array('nid', 'vid'));
  $location = $query->execute()->fetchAll();

Switch back to Drupal 8 database connection:

// Switch back
\Drupal\Core\Database\Database::setActiveConnection();
Code to update locations in Drupal 8 database:
 // Query to import locations
  $last_location = count($location);
  foreach ($location as $key => $value) {
    // UK code is changed to GB in Drupal 8
    if ($value->country == 'uk') {
      $value->country = 'GB';
    }
    $node = node_load($value->nid);
    
    db_merge('node__field_location')
      ->key(array('entity_id' => $value->nid))
      ->fields(array(
          'bundle' => $node->getType(),
          'deleted' => '0',
          'entity_id' => $value->nid,
          'revision_id' => $value->vid,
          'langcode' => 'en',
          'delta' => '0',
          'field_location_address_line1' => $value->name,
          'field_location_address_line2' => $value->street,
          'field_location_locality' => $value->city,
          'field_location_postal_code' => $value->postal_code,
          'field_location_country_code' => strtoupper($value->country),
      ))
      ->execute();

    db_merge('node_revision__field_location')
      ->key(array('entity_id' => $value->nid))
      ->fields(array(
          'bundle' => $node->getType(),
          'deleted' => '0',
          'entity_id' => $value->nid,
          'revision_id' => $value->vid,
          'langcode' => 'en',
          'delta' => '0',
          'field_location_address_line1' => $value->name,
          'field_location_address_line2' => $value->street,
          'field_location_locality' => $value->city,
          'field_location_postal_code' => $value->postal_code,
          'field_location_country_code' => strtoupper($value->country),
      ))
      ->execute();

    // Show a message on screen once all the locations are updated.
    if ($key == ($last_location - 1)) {
      drupal_set_message('Migrated locations');
    }
  }
Note: I had same nids on drupal 6 & drupal 8 site as i used drupal 8 core migration.

4. Run Cron to import all locations.

Here is the full code written in hook_cron():
function MODULENAME_cron() {
  // Switch to external database
  \Drupal\Core\Database\Database::setActiveConnection('external');

  // Get a connection going
  $db = \Drupal\Core\Database\Database::getConnection();

  // Query to fetch all locations
  $query = $db->select('location', 'l');
  $query->join('location_instance', 'li', 'l.lid = li.lid');
  $query->fields('l', array('name', 'street', 'additional', 'city', 'province', 'postal_code', 'country', 'latitude', 'longitude'));
  $query->fields('li', array('nid', 'vid'));
  $location = $query->execute()->fetchAll();

  // Switch back
  \Drupal\Core\Database\Database::setActiveConnection();

  // Query to import locations
  $last_location = count($location);
  foreach ($location as $key => $value) {
    // UK code is changed to GB in Drupal 8
    if ($value->country == 'uk') {
      $value->country = 'GB';
    }
    $node = node_load($value->nid);
    
    db_merge('node__field_location')
      ->key(array('entity_id' => $value->nid))
      ->fields(array(
          'bundle' => $node->getType(),
          'deleted' => '0',
          'entity_id' => $value->nid,
          'revision_id' => $value->vid,
          'langcode' => 'en',
          'delta' => '0',
          'field_location_address_line1' => $value->name,
          'field_location_address_line2' => $value->street,
          'field_location_locality' => $value->city,
          'field_location_postal_code' => $value->postal_code,
          'field_location_country_code' => strtoupper($value->country),
      ))
      ->execute();

    db_merge('node_revision__field_location')
      ->key(array('entity_id' => $value->nid))
      ->fields(array(
          'bundle' => $node->getType(),
          'deleted' => '0',
          'entity_id' => $value->nid,
          'revision_id' => $value->vid,
          'langcode' => 'en',
          'delta' => '0',
          'field_location_address_line1' => $value->name,
          'field_location_address_line2' => $value->street,
          'field_location_locality' => $value->city,
          'field_location_postal_code' => $value->postal_code,
          'field_location_country_code' => strtoupper($value->country),
      ))
      ->execute();

    // Show a message on screen once all the locations are updated.
    if ($key == ($last_location - 1)) {
      drupal_set_message('Migrated locations');
    }
  }
}

 

Hope this code helps you to make things work..!!! Need more assistance regarding web development service…!

Drupal 7 – Data Migration Through Feeds

Working with Drupal, often times we are required to import a large set of data in site. We have various ways to import data. Feeds module is simple and easy to use. Feeds out of the box supports many features which can cover a variety of scenarios. The module is well documented and you can access documentation here.

 

In this part, we are going to explain basics for how to import data using feeds.
To use feeds module, we need ctools and job scheduler module enabled.
The first step in the process is to turn required modules enabled. Enable Feeds, Feeds Admin UI. If you want an example of node importer and user importer then turn Feeds Import enabled.

 

Next step is to add an importer that lets you import data. To do this, go to “admin/structure/feeds” and click on “Add importer”. If you have turned Feeds Import on, you will see example importers here.
Next step is to configure importer. There are various parts in this.
  1. Basic Settings
  2. Fetcher
  3. Parser
  4. Processor
Each is explained in detail below:
These are basic settings for importers:
Name and description are what you specified while creating the importer. “Attach to content type” is used to determine whether we want to attach importer to any content type form or use standalone form.
We use the standalone form if we want to import by using a form that comes with the custom drupal module development at /import path. If we go with content type then import is executed by creating a node of selected content type.
Periodic updates are used to run import periodically. Proper cron configuration is required to run periodic updates. Keep periodic updates off if you are importing data one time only.
Import on submission will start importing process as soon as the form is submitted. There is an option to run the process in the background. This is particularly helpful when importing large data.
Fetcher
The Fetcher is where your feed is fetched from. We have two options here: File upload and HTTP fetcher.
We get a template sample on this page which helps in CSV file construction. Upload the CSV file in required format and import content. Upon completion, a status message is displayed.
In case, we want to delete all nodes that we imported we can do so by going to “Delete Items” tab on import page.
Feeds module out of the box provides many features and is very powerful. There are various other modules available that enhances feeds module functionality.
Hope this helps you, feel free to share your valuable feedback and inputs.
For read more, Click Here