Skip to content

Instantly share code, notes, and snippets.

@keopx
Forked from crittermike/import.php
Last active September 20, 2023 12:47
Show Gist options
  • Save keopx/085852c4455fc6baaad421a0e9c46c8d to your computer and use it in GitHub Desktop.
Save keopx/085852c4455fc6baaad421a0e9c46c8d to your computer and use it in GitHub Desktop.
Importing Drupal 8 config programmatically
<?php
// Import arbitrary config from a variable.
// Assumes $data has the data you want to import for this config.
$config = \Drupal::service('config.factory')->getEditable('filter.format.basic_html');
$config->setData($data)->save();
// Or, re-import the default config for a module or profile, etc.
\Drupal::service('config.installer')->installDefaultConfig('module', 'my_custom_module');
// Or, import YAML config from an arbitrary file.
$config_path = drupal_get_path('module', 'my_custom_module') . '/config/install';
$source = new FileStorage($config_path);
$config_storage = \Drupal::service('config.storage');
$config_storage->write('filter.format.basic_html', $source->read('filter.format.basic_html'));
// Install optional config.
$config_path = drupal_get_path('module', 'MY_MODULE') . '/config/optional';
$config_source = new \Drupal\Core\Config\FileStorage($config_path);
\Drupal::service('config.installer')->installOptionalConfig($config_source);
@jayakrishnanj
Copy link

On Drupal 10 , I use below code

  // Install optional config.
  $path_to_module = \Drupal::service('extension.path.resolver')->getPath('module', 'MODULE_NAME');
  $config_path = $path_to_module . '/config/optional';
  $config_source = new \Drupal\Core\Config\FileStorage($config_path);
  \Drupal::service('config.installer')->installOptionalConfig($config_source);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment