How to create a field with hook_update?

by albertski   Last Updated September 12, 2017 15:07 PM

I want to create a field with hook_update in my module. I have the following code that creates the configuration for a field_link field:

$module_path = drupal_get_path('module', 'my_module');
$configs['field.field.paragraph.image.field_link'] = $module_path . '/config/install/field.field.paragraph.image.field_link.yml';
$configs['field.storage.paragraph.field_link'] = $module_path . '/config/install/field.storage.paragraph.field_link.yml';

foreach ($configs as $name => $config_path) {
  $data = Yaml::parse($config_path);
  $config = \Drupal::configFactory()->getEditable($name);
  $config->setData($data)->save(TRUE);
}

As far as configuration it seems to be working correctly. When I try to create a node it all displays as it should. But if you save, you get an error that the table doesn't exist. Perhaps I have to use the ConfigInstaller class. Anyone know how to have the table get created?



Answers 3


Don't use the low-level config, that doesn't trigger the necessary API calls.

Use FieldConfig::create() and FieldStorageConfig::create()

Berdir
Berdir
February 06, 2017 20:01 PM

Thanks @Berdir. I was able to create the field with FieldConfig & FieldStorageConfig classes.

$module_path = drupal_get_path('module', 'my_module');

$yml = Yaml::parse(file_get_contents($module_path . '/config/install/field.storage.paragraph.field_link.yml'));
if (!FieldStorageConfig::loadByName($yml['entity_type'], $yml['field_name'])) {
  FieldStorageConfig::create($yml)->save();
}
$yml = Yaml::parse(file_get_contents($module_path . '/config/install/field.field.paragraph.image.field_link.yml'));
if (!FieldConfig::loadByName($yml['entity_type'], $yml['bundle'], $yml['field_name'])) {
  FieldConfig::create($yml)->save();
}
albertski
albertski
February 11, 2017 20:31 PM

Rather than use the Yaml class directly, it's better to use FieldStorage:

$config_path = drupal_get_path('module', 'my_module') . '/config/install';
$storage = new FileStorage($config_path);

// Note: .yml extension not needed.
$data = $source->read('field.storage.paragraph.field_link');

if (!FieldStorageConfig::loadByName($data['entity_type'], $data['field_name'])) {
  FieldStorageConfig::create($data)->save();
}
Tim
Tim
September 12, 2017 14:45 PM

Related Questions



Using Configuration API in drupal 8

Updated June 15, 2015 23:03 PM