Skip to content

Instantly share code, notes, and snippets.

@dstorozhuk
Forked from crittermike/import.php
Last active May 8, 2020 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dstorozhuk/18e38ca82a624c858d14cf26194a016b to your computer and use it in GitHub Desktop.
Save dstorozhuk/18e38ca82a624c858d14cf26194a016b 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'));
// Create a fieds from config.
use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Config\FileStorage;
/**
* Implement hook_install().
*/
function client_business_logic_install() {
// Obtain configuration from yaml files
$config_path = 'path/to/config';
$source = new FileStorage($config_path);
// Obtain the storage manager for vocabularies
// Create a new vocabulary from the yaml configuration and save
\Drupal::entityManager()->getStorage('taxonomy_vocabulary')
->create($source->read('taxonomy.vocabulary.business_logic_vocab'))
->save();
// Obtain the storage manager for field storage bases
// Create a new field from the yaml configuration and save
\Drupal::entityManager()->getStorage('field_storage_config')
->create($source->read('field.storage.taxonomy_term.field_machine_name'))
->save();
// Obtain the storage manager for field instances
// Create a new field instance from the yaml configuration and save
\Drupal::entityManager()->getStorage('field_config')
->create($source->read('field.field.taxonomy_term.business_logic_vocab.field_machine_name'))
->save();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment