You are here

function flag_lists_update_8001 in Flag Lists 8

Same name and namespace in other branches
  1. 4.0.x flag_lists.install \flag_lists_update_8001()

Change the name of bundle to type in flag_list_item.

File

./flag_lists.install, line 13
Contains install and updates for Flag Lists module.

Code

function flag_lists_update_8001() {
  $entity_type_manager = \Drupal::entityTypeManager();
  $bundle_of = 'flag_list_item';
  $storage = $entity_type_manager
    ->getStorage($bundle_of);
  $bundle_definition = $entity_type_manager
    ->getDefinition($bundle_of);

  // Sometimes the primary key isn't 'id'. e.g. 'eid' or 'item_id'.
  $id_key = $bundle_definition
    ->getKey('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.
  $type_values = $database
    ->select($table_name)
    ->fields($table_name, [
    $id_key,
    'bundle',
  ])
    ->execute()
    ->fetchAllKeyed();

  // Clear out the values.
  $database
    ->update($table_name)
    ->fields([
    'bundle' => NULL,
  ])
    ->execute();

  // Uninstall the field.
  $field_storage_definition = $definition_manager
    ->getFieldStorageDefinition('bundle', $bundle_of);
  $definition_manager
    ->uninstallFieldStorageDefinition($field_storage_definition);

  // Create a new field definition.
  $new_type_field = BaseFieldDefinition::create('string')
    ->setLabel(t('Entity type'))
    ->setDescription(t('The entity type.'))
    ->setDefaultValue('no')
    ->setRevisionable(FALSE)
    ->setTranslatable(FALSE);

  // Install the new definition.
  $definition_manager
    ->installFieldStorageDefinition('type', $bundle_of, $bundle_of, $new_type_field);
  foreach ($type_values as $id => $value) {
    $database
      ->update($table_name)
      ->fields([
      'type' => $value,
    ])
      ->condition($id_key, $id)
      ->execute();
  }
  $message = "Converted Flag List Item table from 'bundle' to 'type'.";
  return $message;
}