Skip to content

Instantly share code, notes, and snippets.

@mgomma
Created December 11, 2018 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgomma/e5f4201f2323110a8fec092996ec639e to your computer and use it in GitHub Desktop.
Save mgomma/e5f4201f2323110a8fec092996ec639e to your computer and use it in GitHub Desktop.
Update entity field definition that has data
function updateBaseFielDefinitions(&$entity_field_data){
ignore_user_abort(TRUE);
set_time_limit(0);
ini_set('max_execution_time', 0);
foreach ($entity_field_data as $k => $field_data) {
$entity_type_manager = \Drupal::entityTypeManager();
$storage = $entity_type_manager->getStorage($field_data['bundle_of']);
$bundle_definition = $entity_type_manager->getDefinition($field_data['bundle_of']);
// Sometimes the primary key isn't 'id'. e.g. 'eid' or 'item_id'.
$id_key = $bundle_definition->getKey($field_data['id']);
// If there is no data table defined then use the base table.
$table_name = $storage->getDataTable() ?: $storage->getBaseTable();
$database = \Drupal::database();
$definition_manager = \Drupal::entityDefinitionUpdateManager();
// Store the existing values.
$entity_field_data[$k]['values'] = $database->select($field_data['table_name'])
->fields($field_data['table_name'], [$id_key, $field_data['field_name']])
->execute()
->fetchAllKeyed();
$filesPath = \Drupal::service('file_system')->realpath(file_default_scheme()."://");
$file_name = $filesPath.'/'.$field_data['table_name'].'-'.$field_data['field_name'];
if(\file_exists($file_name)){
\rename($file_name, $file_name.'-bak-'.time());
}
\file_put_contents($file_name, \serialize($field_data[$k]['values']));
//$q = 'ALTER TABLE vat_refund_entity MODIFY item_space varchar(255) null';
//\Drupal::database()->query($q)->execute();
// Clear out the values.
$database->update($field_data['table_name'])
->fields([$field_data['field_name'] => NULL])
->execute();
}
\Drupal::service('entity.definition_update_manager')->applyUpdates();
foreach ($entity_field_data as $field_data) {
foreach ($field_data['values'] as $id => $value) {
$database->update($field_data['table_name'])
->fields([$field_data['field_name'] => $value])
->condition($field_data['id'], $id)
->execute();
}
}
drupal_flush_all_caches();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment