I want to create a text field to videos with code. I have the following in the .install file in a custom module:
function video_update_8101() {
$field_name = 'field_video_alternative_text';
// Make sure the field doesn't already exist.
if (!FieldStorageConfig::loadByName('file', $field_name)) {
// Create the field.
$field = FieldStorageConfig::create(array(
'field_name' => $field_name,
'type' => 'text',
'settings' => array('max_length' => 64),
));
$field->save();
// Create the instance.
$instance = FieldStorageConfig::create(array(
'field_name' => $field_name,
'entity_type' => 'file',
'bundle' => 'video',
'label' => 'Alternative tekst',
'description' => 'En beskrivelse kommer her.',
'required' => TRUE,
));
$instance->save();
}
}
I get the following when running update.php
Attempt to create a field storage field_video_alternative_text with no entity_type. [error]
Performing emu_video_update_8101 [ok]
Failed: Attempt to create a field storage field_video_alternative_text with no entity_type.
Furthermore, I want this to happen when I install the module. I suppose it's not at this point?
Edit: I got inspiration from this post: How do programmatically create fields for content types, and ADD them to the the content type form
hook_update_N
is for updates only, they won't be executed upon install. The point of them is to allow older versions of the module to get up to date with the current version that they're upgrading to. The initial state of the latest version of the module should reflect the state the older version of the module would be in after the update. Thinkhook_install
or config/install/*.ymlhook_uninstall
, or at least checking whether it exists first before creating inhook_install
. Just in case you need to reinstall the module