Created
May 7, 2022 16:25
-
-
Save vishwac09/15dd19d7ae3507ac85bddf4b77319da7 to your computer and use it in GitHub Desktop.
ChangeBaseFieldType
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function vehicle_update_8001() { | |
$database = \Drupal::database(); | |
$transaction = $database->startTransaction(); | |
$entity_type_manager = \Drupal::entityTypeManager(); | |
// The entity whose field type needs to be updated. | |
$bundle_of = 'vehicle'; | |
$storage = $entity_type_manager->getStorage($bundle_of); | |
$bundle_definition = $entity_type_manager->getDefinition($bundle_of); | |
// The primary id of the table. | |
$id_key = $bundle_definition->getKey('id'); | |
// If there is no data table defined then use the base table. | |
$table_name = $storage->getDataTable() ?: $storage->getBaseTable(); | |
$definition_manager = \Drupal::entityDefinitionUpdateManager(); | |
// Store the existing values. | |
$vehiclesCC = $database->select($table_name) | |
->fields($table_name, [$id_key, 'cc']) | |
->execute() | |
->fetchAllKeyed(); | |
// Clear out the values. Empty all the values before removing the field. | |
$database->update($table_name) | |
->fields(['cc' => NULL]) | |
->execute(); | |
// Uninstall the field from the Entity. | |
$field_storage_definition = $definition_manager->getFieldStorageDefinition('vehicle', $bundle_of); | |
$definition_manager->uninstallFieldStorageDefinition($field_storage_definition); | |
// Create a new field definition. | |
$new_status_field = BaseFieldDefinition::create('decimal') | |
->setLabel(t('CC')) | |
->setDescription(t('The capacity of the engine in cubic centimeter.')) | |
->setDefaultValue(0.0) | |
->setRevisionable(FALSE) | |
->setTranslatable(FALSE); | |
// Install the new definition. | |
$definition_manager->installFieldStorageDefinition('vehicle', $bundle_of, $bundle_of, $new_status_field); | |
foreach ($vehiclesCC as $id => $value) { | |
$database->update($table_name) | |
->fields(['cc' => $value]) | |
->condition($id_key, $id) | |
->execute(); | |
} | |
// Commit transaction. | |
unset($transaction); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment