Snippets

Metadrop Drupal 8 - Programmatically create fields from existing config.

Created by David López last modified Alejandro Cabarcos
<?php

// Create the new FIELD_NAME field.
$dir = DRUPAL_ROOT . '/../config/default/';
$field_name = 'FIELD_NAME';
$entity_type = 'ENTITY_TYPE';
$bundle = 'BUNDLE';

$field_storage_entity = 'field.storage.' . $entity_type . '.' . $field_name;
$field_entity = 'field.field.' . $entity_type . '.' . $bundle . '.' . $field_name;

// Create the new fields based on the existing configuration files.
$yml = Yaml::parse(file_get_contents($dir . $field_storage_entity . '.yml'));
if (!FieldStorageConfig::loadByName($yml['entity_type'], $yml['field_name'])) {
    FieldStorageConfig::create($yml)->save();
}
$yml = Yaml::parse(file_get_contents($dir . $field_entity . '.yml'));
if (!FieldConfig::loadByName($yml['entity_type'], $yml['bundle'], $yml['field_name'])) {
    FieldConfig::create($yml)->save();
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.