Skip to content

Instantly share code, notes, and snippets.

@ericmorand
Last active May 15, 2019 10:18
Show Gist options
  • Save ericmorand/e0dfef76fb246cddb861f40dd9975958 to your computer and use it in GitHub Desktop.
Save ericmorand/e0dfef76fb246cddb861f40dd9975958 to your computer and use it in GitHub Desktop.
Drupal 8 - Update a field type with data
<?php
$database = Drupal::database();
$entity_type = 'paragraph';
$field_name = 'field_value';
$table = $entity_type . '__' . $field_name;
$field_storage = FieldStorageConfig::loadByName($entity_type, $field_name);
if (is_null($field_storage)) {
return;
}
$rows = NULL;
if ($database->schema()->tableExists($table)) {
// The table data to restore after the update is completed.
$rows = $database->select($table, 'n')
->fields('n')
->execute()
->fetchAll();
}
$new_fields = array();
// Use existing field config for new field.
foreach ($field_storage->getBundles() as $bundle => $label) {
$field = FieldConfig::loadByName($entity_type, $bundle, $field_name);
$new_field = $field->toArray();
$new_field['field_type'] = 'decimal';
$new_field['settings'] = array();
$new_fields[] = $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. You may need to increase batch size.
field_purge_batch(10);
// Create new field storage.
$new_field_storage = FieldStorageConfig::create($new_field_storage);
$new_field_storage->save();
// Create new fields.
foreach ($new_fields as $new_field) {
$new_field = FieldConfig::create($new_field);
$new_field->save();
}
// Restore existing data in the same table.
if (!is_null($rows)) {
foreach ($rows as $row) {
$database->insert($table)
->fields((array)$row)
->execute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment