I’m trying to implement this in a hook_update_N()
but I’m not sure it’s proper (see excerpt below). Note I’m changing max_length in the process.
What I'm trying to do: update my_custom_entity.field_my_custom_field which has saved data into it. So I need to:
- Store that data
- Store the field configs - if that’s possible?
- Store the field storage - if that’s possible?
- Delete the field
- Create the field again using stored configs and storage
- Restore the saved data
// Capture the existing field configs.
$field = FieldConfig::loadByName($entity_type, $bundle, $field_name);
$new_field = $field->toArray();
$new_field['field_type'] = 'string';
$new_field['settings'] = [];
// Capture the existing field storage.
$new_field_storage = $field_storage->toArray();
$new_field_storage['type'] = 'string';
$new_field_storage['settings'] = [
'max_length' => $field_length,
'is_ascii' => FALSE,
'case_sensitive' => FALSE,
];
// Delete existing field + field storage and purge data.
$field_storage->delete();
field_purge_batch(150);
// Create new field using captured configs/settings.
$new_field_storage = FieldStorageConfig::create($new_field_storage);
$new_field_storage->save();
$new_field = FieldConfig::create($new_field);
$new_field->save();