Tag: drupal web design services

Guidelines for Updating Node Fields Without node_save() In Drupal

Guidelines for Updating Node Fields Without node_save() In Drupal

Customization is nowadays common on Drupal site. Here you may need to save node programmatically at any time. For saving node programmatically we use node_save() hook which will save the whole node though we want to update only one field.

Drupal function field_attach_update() will replace node_save() in some way. It will update only that field which you want to update.

Benefits of field_attach_update()

  1. Reduces load time.
  2. Not update CCK fields.
  3. Easy to use.

Below is the code to use field_attach_update() hook.

// $arr_nids is array of node id that you want to update
$arr_nodes = node_load_multiple($arr_nids);
foreach ($arr_nodes as $key => $node) {
$node->field_fieldname1[LANGUAGE_NONE][0]['value'] = 'field1 value';
$node->field_fieldname2[LANGUAGE_NONE][0]['value'] = 'field2 value';
$node->field_fieldname3[LANGUAGE_NONE][0]['value'] = 'field3 value';

field_attach_update('node', $node);
entity_get_controller('node')->resetCache(array($node->nid));
}

entity_get_controller(‘node’)->resetCache(array($node->nid)) is used to clear cache for the entity.

For example:

Values before using field_attach_update():

Guidelines for Updating Node Fields Without node_save() In Drupal

Update Fields using field_attach_update():

$nid = '29';
$node = node_load($nid);
$node->field_fname[LANGUAGE_NONE][0]['value'] = 'Johnny1';
$node->field_lname[LANGUAGE_NONE][0]['value'] = 'Harper1';
$node->field_address[LANGUAGE_NONE][0]['value'] = '405, Silicon Tower, Above Freezland Restaurant, Law Garden, Off C.G. road, Ahmedabad, Gujarat - 380009 India.';

field_attach_update('node', $node);
entity_get_controller('node')->resetCache(array($node->nid));

Values after using field_attach_update():

Guidelines for Updating Node Fields Without node_save() In Drupal

Hope this helped you to get most out of the system. Need more assistance for Drupal Development Services then get in touch with us. Feel free to share your reviews and pick the best answer for your requirements. #WeDrupalEveryday

Advertisements

Create Custom Multistep Form Using Ajax

Multistep Form Using Ajax
Don’t want long forms on your website? Convert it into multi-step form, as it is more convenient and provides step by

step procedure to follow by user. This blog will provide a way to create of multi step form using ajax.

https://goo.gl/P1BrVx 1. Create a menu item using hook_menu()

/** * Implementation of hook_menu(). */ function custom_menu() { $menu[‘multistep_form’] = array ( ‘title’ => ‘Multistep Form’, ‘description’ => ‘To create multistep form’, ‘page callback’ => ‘drupal_get_form’, ‘page arguments’ => array(‘ajax_multistep_form’), ‘access callback’ => TRUE, ); return $menu; }

  1. Define a callback functionIt includes stepwise fields. It contains fieldset for each step with their respective fields. Then It will includes buttons for each step.

We have called ajax_multistep_form_ajax_callback function it returns the entire form each time the function is called. Added a wrapper div “ajax_multistep_form’” to update the form using AJAX.

$form[‘buttons’][‘next’] = array ( ‘#type’ => ‘submit’, ‘#value’ => t(‘Next’), ‘#ajax’ => array ( ‘wrapper’ => ‘ajax_multistep_form’, ‘callback’ => ‘ajax_multistep_form_ajax_callback’, ), );

 

 

function ajax_multistep_form($form, &$form_state) {   // If $form_state[‘step’] is not set then set default to 1 $form_state[‘step’] = isset($form_state[‘step’]) ? $form_state[‘step’] : 1; // Add a wrapper div to update the form using AJAX $form[‘#prefix’] = ‘

‘; $form[‘#suffix’] = ‘

‘;   switch($form_state[‘step’]) { // Step 1 case 1: $fname_default_value = $lname_default_value = ”; if(isset($form_state[‘values’][‘step_1’])) { $fname_default_value = $form_state[‘values’][‘step_1’][‘fname’]; $lname_default_value = $form_state[‘values’][‘step_1’][‘lname’]; } elseif(isset($form_state[‘storage’][‘step_1’])) { $fname_default_value = $form_state[‘storage’][‘step_1’][‘fname’]; $lname_default_value = $form_state[‘storage’][‘step_1’][‘lname’]; }   $form[‘step_1’] = array( ‘#type’ => ‘fieldset’, ‘#title’ => t(”), ‘#collapsible’ => false, ‘#collapsed’ => false, ); $form[‘step_1’][‘fname’] = array( ‘#type’=>’textfield’, ‘#required’ => true, ‘#title’=>t(‘First Name’), ‘#default_value’ => $fname_default_value, ); $form[‘step_1’][‘lname’] = array( ‘#type’=>’textfield’, ‘#required’ => true, ‘#title’=>t(‘Last name’), ‘#default_value’ => $lname_default_value, ); break; // Step 2 case 2: $phone_default_value = ”; if(isset($form_state[‘values’][‘step_2’])) { $phone_default_value = $form_state[‘values’][‘step_2’][‘phone’]; } elseif(isset($form_state[‘storage’][‘step_2’])) { $phone_default_value = $form_state[‘storage’][‘step_2’][‘phone’]; }   $form[‘step_2’] = array( ‘#type’ => ‘fieldset’, ‘#title’ => t(”), ‘#collapsible’ => false, ‘#collapsed’ => false, ); $form[‘step_2’][‘phone’] = array( ‘#type’=>’textfield’, ‘#required’ => true, ‘#title’=>t(‘Phone Number’), ‘#default_value’ => $phone_default_value, ); break; // Step 3 case 3: $city_default_value = $city_default_value = ”; if(isset($form_state[‘values’][‘step_3’])) { $street_default_value = $form_state[‘values’][‘step_3’][‘street’]; $city_default_value = $form_state[‘values’][‘step_3’][‘city’]; } elseif(isset($form_state[‘storage’][‘step_3’])) { $street_default_value = $form_state[‘storage’][‘step_3’][‘street’]; $city_default_value = $form_state[‘storage’][‘step_3’][‘city’]; }   $form[‘step_3’] = array( ‘#type’ => ‘fieldset’, ‘#title’ => t(”), ‘#collapsible’ => false, ‘#collapsed’ => false, ); $form[‘step_3’][‘street’] = array( ‘#type’=>’textfield’, ‘#required’ => true, ‘#title’=>t(‘Street Address’), ‘#default_value’ => $street_default_value, );   $form[‘step_3’][‘city’] = array( ‘#type’=>’textfield’, ‘#required’ => true, ‘#title’=>t(‘City’), ‘#default_value’ => $city_default_value, );   }     // Form Buttons $form[‘buttons’] = array ( ‘#type’ => ‘container’, ); // If we are on step 1, we do not want a back button if($form_state[‘step’] !== 1) { $form[‘buttons’][‘back’] = array ( ‘#type’ => ‘submit’, ‘#value’ => t(‘Back’), ‘#limit_validation_errors’ => array(), ‘#submit’ => array(‘ajax_multistep_form_back_submit’), ‘#ajax’ => array ( ‘wrapper’ => ‘ajax_multistep_form’, ‘callback’ => ‘ajax_multistep_form_ajax_callback’, ), ); }   if($form_state[‘step’] !== 3) { $form[‘buttons’][‘next’] = array ( ‘#type’ => ‘submit’, ‘#value’ => t(‘Next’), ‘#ajax’ => array ( ‘wrapper’ => ‘ajax_multistep_form’, ‘callback’ => ‘ajax_multistep_form_ajax_callback’, ), ); } else { $form[‘buttons’][‘submit’] = array ( ‘#type’ => ‘submit’, ‘#value’ => t(‘Submit’), ‘#ajax’ => array ( ‘wrapper’ => ‘ajax_multistep_form’, ‘callback’ => ‘ajax_multistep_form_ajax_callback’, ), ); } return $form; }

  1. Add validation for your fieldsIt will add validation for phone number field in step 2. You can add validations for other steps too.

function ajax_multistep_form_validate($form, &$form_state) { switch($form_state[‘step’]) { case “2”: $contact_phone = $form_state[‘values’][‘phone’]; $contact_errror = ‘”‘.$contact_phone .'”‘ . ‘ is not a valid North American phone number. Please enter a valid ten-digit phone number with optional extension in this format 123 456 7891.’; if (!preg_match(‘/([0-9]{3}?\s?[0-9]{3}?\s?[0-9]{4})/’, $contact_phone)) { form_set_error(‘phone’, $contact_errror); } break; } }

  1. Final submit function

function ajax_multistep_form_submit($form, &$form_state) {   $step = $form_state[‘step’];   //$form_state[‘storage’][‘step_’ . $step] = $form_state[‘step’];   if($form_state[‘step’] == 1) { $form_state[‘storage’][‘step_’ . $step][‘fname’] = $form_state[‘values’][‘fname’]; $form_state[‘storage’][‘step_’ . $step][‘lname’] = $form_state[‘values’][‘lname’];   } if($form_state[‘step’] == 2) { $form_state[‘storage’][‘step_’ . $step][‘phone’] = $form_state[‘values’][‘phone’]; }   if(isset($form_state[‘values’][‘next’]) && $form_state[‘values’][‘op’] == $form_state[‘values’][‘next’]) { // Goto next step $form_state[‘step’]++; }   if(isset($form_state[‘values’][‘back’]) && $form_state[‘values’][‘op’] == $form_state[‘values’][‘back’]) { // Goto next step $form_state[‘step’]–; } // Check if it is last step elseif(isset($form_state[‘values’][‘submit’]) && $form_state[‘values’][‘op’] == $form_state[‘values’][‘submit’]) {   $form_state[‘storage’][‘step_’ . $step][‘street’] = $form_state[‘values’][‘street’]; $form_state[‘storage’][‘step_’ . $step][‘city’] = $form_state[‘values’][‘city’];   $items = array($form_state[‘storage’][‘step_1’][‘fname’], $form_state[‘storage’][‘step_1’][‘lname’], $form_state[‘storage’][‘step_2’][‘phone’], $form_state[‘storage’][‘step_3’][‘street’], $form_state[‘storage’][‘step_3’][‘city’]); drupal_set_message(t(‘You submitted the following values:!values’, array(‘!values’ => theme(‘item_list’, array(‘items’ => $items)))));   $form_state[‘step’] = 1; $form_state[‘storage’] = array(); } $form_state[‘rebuild’] = TRUE; }

  1. Ajax callback function for every buttons in our form

function ajax_multistep_form_ajax_callback($form, &$form_state) { return $form; }

This it just an example, you store all steps value in “$form_state[‘storage’]” and use it.

$step = $form_state[‘step’]; $form_state[‘storage’][‘step_’ . $step][‘values’] = $form_state[‘values’];

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

CakePHP development services then get in touch with us. #WeDrupalEveryday. Pick the best answer for your requirements.

Tips To Upgrade Commerce Coupon Module In Drupal

Commerce Coupon Module

Commerce coupon module adds Commerce coupon facility to Drupal commerce.

Commerce coupon 7.x-2.x is recommended version. This version depends on Commerce Discount.

Commerce coupon 7.x-2.x has many architectural improvements and new features which include integration with commerce discount, multiple discounts per coupon, integration with inline conditions.

There are no fixed amount coupons or percentage coupons with this version. Instead, we use discounts and use them with coupons.

Upgrading from Commerce coupon 7.x-1.x to Commerce coupon 7.x-2.x is not directly supported. It is two step process.

As per module page on drupal.org, “Commerce Coupon 7.x-2.x-beta2 has an upgrade path from 1.x to 2.x. It works for upgrading relatively simple coupon 1.x sites; mileage may vary if you have a lot of custom coupon functionality though.”

So in order to upgrade to latest commerce coupon, we first need to upgrade to beta2 and then upgrade to latest version.

Below are the steps to upgrade normal commerce coupon setup without any additional customization.

  • First things first, take a backup.
  • Upgrade to Commerce coupon 7.x-2.x-beta3 following standard upgrade process. You will need to add commerce discounts and inline conditions modules installed before upgrading commerce coupon.
  • Once updates are run, you will see your old coupons converted into new coupon and discount systems. Discounts are created for previous fixed and percentage coupons.
  • Upgrade to latest commerce coupon version following standard upgrade process.
  • Make sure to give permission to required user roles to “Redeem coupon”.

This process assumes that there is no custom coupon functionality is added and no additional modules are used along-w

ith commerce coupon. The Success of upgrade process largely depends on how coupon module is used and customization is done on it.

Below are the steps to upgrade commerce coupon with Commerce Coupon by product reference module installed.

  • Take a backup.
  • Delete product reference fields from coupons.
  • Disable Commerce Coupon by product reference module.
  • Upgrade commerce coupon as outlined in steps 2,3 and 4 in upgrade normal commerce coupon.
  • Edit required discounts and add products.

This makes sure that this discount applies to specific products only.

  • Give appropriate user roles permission to “Redeem coupon”.

Since inline conditions are also installed, you can create coupons while creating discounts.

You can also consider adding Commerce discount Extra module which provides various common discount condition And offers types.

Need more assistance regarding Drupal Commerce Module Development Contact us now and Feel free to share your views/feedback for any further queries.

Guide To Customize Google Map Style And Custom Zoom Bar

custom-zoom

Google map theming and configuration with custom zoom controls, please follow the below details:

Styling google map allows us to change standard google map style and customize maps visual display like road, water, park and etc.

To make changes in standard google map style, we can use json array as per below:

var styledMapType = new google.maps.StyledMapType([
  { elementType: 'geometry', stylers: [{color: '#EBE5E2'}]},
  { elementType: 'labels.text.fill', stylers: [{color: '#520000'}]},
  { elementType: 'labels.text.stroke', stylers: [{color: '#F5E8DA'}]},
  {
    featureType: 'administrative',
    elementType: 'geometry.stroke',
    stylers: [{color: '#C9A193'}]
  },
  {
    featureType: 'administrative.land_parcel',
    elementType: 'geometry.stroke',
    stylers: [{color: '#DCD6B2'}]
  },
  {
    featureType: 'administrative.land_parcel',
    elementType: 'labels.text.fill',
    stylers: [{color: '#AEA5A0'}]
  },
  {
    featureType: 'landscape.natural',
    elementType: 'geometry',
    stylers: [{color: '#DFDFBB'}]
  },
  {
    featureType: 'poi',
    elementType: 'geometry',
    stylers: [{color: '#DFC47F'}]
  },
  {
    featureType: 'poi',
    elementType: 'labels.text.fill',
    stylers: [{color: '#93746E'}]
  },
  {
    featureType: 'poi.park',
    elementType: 'geometry.fill',
    stylers: [{color: '#9DB04A'}]
  },
  {
    featureType: 'poi.park',
    elementType: 'labels.text.fill',
    stylers: [{color: '#197515'}]
  },
  {
    featureType: 'road',
    elementType: 'geometry',
    stylers: [{color: '#F5E4BF'}]
  },
  {
    featureType: 'road.arterial',
    elementType: 'geometry',
    stylers: [{color: '#FDFBF3'}]
  },
  {
    featureType: 'road.highway',
    elementType: 'geometry',
    stylers: [{color: '#F8C452'}]
  },
  {
    featureType: 'road.highway',
    elementType: 'geometry.stroke',
    stylers: [{color: '#E9BF79'}]
  },
  {
    featureType: 'road.highway.controlled_access',
    elementType: 'geometry',
    stylers: [{color: '#E97741'}]
  },
  {
    featureType: 'road.highway.controlled_access',
    elementType: 'geometry.stroke',
    stylers: [{color: '#DBA37F'}]
  },
  {
    featureType: 'road.local',
    elementType: 'labels.text.fill',
    stylers: [{color: '#80544F'}]
  },
  {
    featureType: 'transit.line',
    elementType: 'geometry',
    stylers: [{color: '#DFCD95'}]
  },
  {
    featureType: 'transit.line',
    elementType: 'labels.text.fill',
    stylers: [{color: '#8F726D'}]
  },
  {
    featureType: 'transit.line',
    elementType: 'labels.text.stroke',
    stylers: [{color: '#EBD9B0'}]
  },
  {
    featureType: 'transit.station',
    elementType: 'geometry',
    stylers: [{color: '#DFD2A9'}]
  },
  {
    featureType: 'water',
    elementType: 'geometry.fill',
    stylers: [{color: '#BAD3C2'}]
  },
  {
    featureType: 'water',
    elementType: 'labels.text.fill',
    stylers: [{color: '#8E9985'}]
  }
]);

Below is the example of google style:

Before style applied

After style applying:

Google map provides ease level of customization.

We can make changes as per our need easily. I have provided an example to configure zoom, scroll, street view and etc options to change default google map.

// Create a map object, and include the MapTypeId to add
// to the map type control.
var map = new google.maps.Map(document.getElementById('gmap'), {
  center: {lat: 23.028349, lng: 72.559097},
  zoom: 11,
  mapTypeControlOptions: {
    mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain', 'styled_map'],
  },
  scrollwheel: true,
  mapTypeControl: true,
  mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
      position: google.maps.ControlPosition.LEFT_TOP
  },
  zoomControl: false,
  // zoomControlOptions: {
  //     style: google.maps.ZoomControlStyle.LARGE,
  //     position: google.maps.ControlPosition.LEFT_TOP
  // },
  scaleControl: true,
  streetViewControl: true,
  streetViewControlOptions: {
      position: google.maps.ControlPosition.LEFT_TOP
  },
  fullscreenControl: false
});

To Add Custom zoom bar:

To add custom zoom bar on the map we can add custom element and use this element we can handle zoom controls.

I have added example code to add custom zoom controls.

// To customize google zoom bar to slider and search controlls
var centerControlDiv = document.createElement('div');
centerControlDiv.setAttribute("class", "gm-custom-controlls");
centerControlDiv.index = 1;

// Add custom zoom controlls
var centerControl = new ZoomControl(centerControlDiv, map, map.minZoom, map.maxZoom, map.zoom);

// map custom controlls to map
map.controls[google.maps.ControlPosition.BOTTOM].push(centerControlDiv);
// Zoom controlls
function ZoomControl(controlDiv, map, min, max, currentZoom) {

  var parentDiv = document.createElement('div');
  parentDiv.setAttribute("class", "gm-zoom-slider");

  var controlUI = document.createElement('input');
  controlUI.type = 'range';
  controlUI.value = currentZoom;
  controlUI.min = min;
  controlUI.max = max;
  controlUI.style.width = "400px";

  // Add zoom controlls
  var incControlls = document.createElement('div');
  incControlls.id = 'gm-zoom-inc';
  incControlls.innerHTML = '+';

  var decControlls = document.createElement('div');
  decControlls.id = 'gm-zoom-dec';
  decControlls.innerHTML = '-';

  parentDiv.appendChild(decControlls);
  parentDiv.appendChild(controlUI);
  parentDiv.appendChild(incControlls);

  controlDiv.appendChild(parentDiv);

  // Click event listner for side-bar
  controlUI.addEventListener('click', function() {
    map.setZoom(parseFloat(controlUI.value));
  });

  // Click event listner for inc button
  incControlls.addEventListener('click', function() {
    map.setZoom(parseFloat(controlUI.value) + 1 );
  });

  // Click event listner for dec button
  decControlls.addEventListener('click', function() {
    map.setZoom(parseFloat(controlUI.value) - 1 );
  });

  // Set slider value on zoom change 
  google.maps.event.addListener(map, 'zoom_changed', function(){
    controlUI.value = map.getZoom();
  });
}

Zoom bar will be displayed as per below screenshot:



Read more regarding Drupal Development Service

How to Use External Invite for User in Drupal 7?

Imagine a scenario where you need to invite some of site users to accept some role on the site. You do not want to go and edit every such users and assign them said role. You also want leave the choice with users if they want to new role on site or not.
Enters User External Invite module.
This module allows users with proper permission to invite other users. Users have specified time before the invite expires. Inviting users also have option to cancel invite and resent invites
Below is step is step guide to install and use this module.
1 – Download the module and install as usual.
Download the module from here: http://drupal.org/project/user_external_invite and install as usual.
2 – Configuration
Go to “admin/people/permissions” and set permission for required roles to send invite.
Go to admin/config/people/invite and set configurations as required.
Select which user roles can be invited, default role, expiration times and templates.
You can customise the emails that will be sent on various occasions here as well.
3 – Invite users
To invite users go to admin/people/invite and add address you want to invite.
You can select role for which invite is being sent. You can also add custom message. This message will be added in email that is being sent to invited users.
4 – Manage Invites
You can manage invites from admin/people/invite/operations.
On this page, you can see list of all invites that are sent and status of each invite. From this page you can either cancel an invite or resent the invite.
The module also implements various checks such as you can not disable module till you have pending invites, making sure that roles are not changed when invites are pending for that role etc.
The module also provides a hook which can be used in case inviting email id is not present in the system.
Hope this article has helped you. Need more assistance regarding drupal development services..!

Amazing HTML Code For Better Design Of Form Fields

Better HTML for better Form Fields

Some form fields look different on certain browser as per its behaviour. Here I have managed same design for all fields in all the browsers.

In this blog, code is provided for all the form fields.

Feature:

  • Support in all browsers and OS & devices (Android & i Phone). I.e. Browser Compatible.
  • Easy to use.
  • SCSS & CSS both codes are available.
  • Compatible with IE 9 and higher version.
  • No need of third party JS, CSS and libraries.

How To Create identical Form fields

  1. Radio button and Checkbox design

Read more…  

https://goo.gl/TRB1T7

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…!