Sunday 26 April 2020

Import Field Configurations Programmatically in Drupal 8

Import Field Configurations Programmatically in Drupal 8


In one of my project, feature module was used to move configurations from one environment to another environment.
With the help of feature module it is easy to move configurations and sync of configurations is easy but when we are moving these configs to production environment we are not having access of it to revert feature changes.

So I decided to write hook_update_n in install file of the module to import configurations of any field. With the help of below code, configurations can be imported to create field.


Create a custom module having below directory structure or place config file in already created custom module in config/install directory and create a modulename.install file

config_import
  config_import.info.yml
  config_import.module
  config_import.install
  config
    install
       // Place all config files here as below
       field.storage.node.field_second_field.yml
       field.field.node.home_stage.field_second_field.yml
       core.entity_form_display.node.home_stage.default.yml
       core.entity_view_display.node.home_stage.default.yml

Code which should available in config_import.install file as below
<?


<?php

/**
 * @file
 * Add search placeholder field.
 */

use Drupal\Core\Config\FileStorage;

/**
 * Add configurations to configs.
 */
function import_config_update_8002() {
  // Get config storage.
  $config_storage = \Drupal::service('config.storage');

  $module = 'import_config';
  // Get config files path.
  $config_path = drupal_get_path('module', 'import_config') . '/config/install';
  // Get file storage for config files.
  $source = new FileStorage($config_path);

  // Create field storage for second field.
  try {
    \Drupal::entityTypeManager()->getStorage('field_storage_config')
      ->create($source->read('field.storage.node.field_second_field'))
      ->save();
  } catch (\Exception $e) {
    Drupal::logger($module)
      ->error('Storage for field field_second_field could not be created. ' . $e->getMessage());
  }

  try {
    // Create field
    \Drupal::entityTypeManager()->getStorage('field_config')
      ->create($source->read('field.field.node.home_stage.field_second_field'))
      ->save();
  } catch (\Exception $e) {
    Drupal::logger($module)
      ->error('Field field_second_field for entity home_stage could not be created. ' . $e->getMessage());
  }

  // Add termscondition field in recipe configurations config pages.
  $config_storage->write('core.entity_form_display.node.home_stage.default', $source->read('core.entity_form_display.node.home_stage.default'));
  $config_storage->write('core.entity_view_display.node.home_stage.default', $source->read('core.entity_view_display.node.home_stage.default'));


}

With above code when you will run drush updb then field "field_second_field" will be created.

For reference :