$database = \Drupal::database(); $entity_type_id = 'basic'; $fields = [ 'employees', 'employees_to_employ', 'average_statistical_number_of_em', ]; foreach ($fields as $field_name) { $old_rows = NULL; $table = $entity_type_id . '__' . $field_name; $new_fields_list = []; $field_storage = FieldStorageConfig::loadByName($entity_type_id, $field_name); if (!$field_storage) { continue; } // Get all current data from DB. if ($database->schema()->tableExists($table)) { // The table data to restore after the update is completed. $old_rows = $database->select($table, 'n') ->fields('n') ->execute() ->fetchAll(); } // Use existing field config for new field. foreach ($field_storage->getBundles() as $bundle => $label) { if ($bundle !== 'partner_data') { continue; } $field = FieldConfig::loadByName($entity_type_id, $bundle, $field_name); $new_field = $field->toArray(); $new_field['field_type'] = 'decimal'; $new_fields_list[] = $new_field; } // Deleting field storage which will also delete bundles(fields). $new_field_storage = $field_storage->toArray(); $new_field_storage['type'] = 'decimal'; $field_storage->delete(); // Purge field data now to allow new field and field_storage with same name // to be created. field_purge_batch(40); // Create new field storage. $new_field_storage = FieldStorageConfig::create($new_field_storage); $new_field_storage->save(); // Create new fields. foreach ($new_fields_list as $new_field) { $new_field_config = FieldConfig::create($new_field); $new_field_config->save(); } // Restore existing data in new table. if ($old_rows) { foreach ($old_rows as $row) { $database->insert($table) ->fields((array) $row) ->execute(); } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter