I am trying to add a default image to an image field in Drupal 8 using the configuration management interface (CMI). Normally once I have a field configured through the admin UI, I would then export the config YAML file for that field so I can add it to my custom module. The issue is that the default image for an image field is content and cannot be directly exported.
If I do export such a file, it would look like this:
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_bluescope_header_bg_image
- node.type.bluescope_page
module:
- image
id: node.bluescope_page.field_bluescope_header_bg_image
field_name: field_bluescope_header_bg_image
entity_type: node
bundle: bluescope_page
label: 'Header background image'
description: 'Image used as the page''s header background'
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
file_directory: images/header-bg
file_extensions: 'png gif jpg jpeg'
max_filesize: ''
max_resolution: ''
min_resolution: ''
alt_field: true
alt_field_required: true
title_field: false
title_field_required: false
default_image:
uuid: 8288b3b1-4b0e-4efc-9137-55cb68382f0a
alt: 'Header background image'
title: ''
width: 1920
height: 1080
handler: 'default:file'
handler_settings: { }
field_type: image
I noted that the default image is referred to using a uuid
. I was thinking that I could address this by programmatically adding the default file to this field's configuration during the module install process. What I tried was to create the image in drupal's file system and then get the uuid
of that file and add it to the fields configuration using configFactory
:
function colorbond_data_install() {
$config_factory = \Drupal::configFactory();
$field_bluescope_header_bg_image_config = $config_factory->getEditable('field.field.node.bluescope_page.field_bluescope_header_bg_image');
$default_image = $field_bluescope_header_bg_image_config->get('settings.default_image');
// Create default image file.
$file_info = colorbond_data_add_file('public://images/header-bg/', 'starwars.jpg', 'Header background image');
$file = File::load($file_info['target_id']);
$default_image['uuid'] = $file->uuid();
$default_image['alt'] = 'Header background image';
$default_image['title'] = 'Header background image';
$default_image['height'] = 1080;
$default_image['width'] = 1920;
$field_bluescope_header_bg_image_config->set('settings.default_image', $default_image);
drupal_flush_all_caches();
}
The problem is that when I reinstall the module, the default image configuration does not appear:
Not sure what I am doing wrong.