$entityType = 'node';
$fieldName = 'field_myfield';
$new_type = 'text_long';
$database = \Drupal::database();
$table = $entityType . '__' . $fieldName;
$rev_table = $entityType . '_revision__' . $fieldName;
$currentRows = NULL;
$newFieldsList = [];
$fieldStorage = FieldStorageConfig::loadByName($entityType, $fieldName);
if (is_null($fieldStorage)) {
return;
}
// Get all current data from DB.
if ($database->schema()->tableExists($table)) {
// The table data to restore after the update is completed.
$currentRows = $database->select($table, 'n')
->fields('n')
->execute()
->fetchAll();
}
// Add for revisions table as well.
if ($database->schema()->tableExists($rev_table)) {
// The table data to restore after the update is completed.
$currentRevRows = $database->select($rev_table, 'n')
->fields('n')
->execute()
->fetchAll();
}
// Use existing field config for new field.
foreach ($fieldStorage->getBundles() as $bundle => $label) {
$field = FieldConfig::loadByName($entityType, $bundle, $fieldName);
$newField = $field->toArray();
$newField['field_type'] = $new_type;
$newField['settings'] = [];
$newFieldsList[] = $newField;
}
// Deleting field storage which will also delete bundles(fields).
$newFieldStorage = $fieldStorage->toArray();
$newFieldStorage['type'] = $new_type;
$newFieldStorage['settings'] = [];
$fieldStorage->delete();
// Purge field data now to allow new field and field_storage with same name
// to be created.
field_purge_batch(50);
// Create new field storage.
$newFieldStorage = FieldStorageConfig::create($newFieldStorage);
$newFieldStorage->save();
// Create new fields.
foreach ($newFieldsList as $nfield) {
$nfieldConfig = FieldConfig::create($nfield);
$nfieldConfig->save();
}
// Restore existing data in new table.
if (!is_null($currentRows)) {
foreach ($currentRows as $row) {
$database->insert($table)
->fields((array) $row)
->execute();
}
}
// And restore existing data in new Revisions table.
if (!is_null($currentRevRows)) {
foreach ($currentRevRows as $row) {
$database->insert($rev_table)
->fields((array) $row)
->execute();
}
}