You are here

function paragraphs_library_update_8001 in Paragraphs 8

Make library items translatable.

File

modules/paragraphs_library/paragraphs_library.install, line 66
Install/Update hooks for paragraphs library.

Code

function paragraphs_library_update_8001() {
  \Drupal::service('entity_type.manager')
    ->clearCachedDefinitions();

  // Load all library items and store their values in memory.
  $library_values = \Drupal::database()
    ->query('SELECT * FROM {paragraphs_library_item}')
    ->fetchAll(PDO::FETCH_ASSOC);

  // Now, truncate the tables to delete the data without invoking APIs that
  // would also delete the referenced paragraphs.
  \Drupal::database()
    ->truncate('paragraphs_library_item')
    ->execute();
  \Drupal::database()
    ->truncate('paragraphs_library_item_revision')
    ->execute();

  // Make the entity type translatable.
  $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $entity_type = $entity_definition_update_manager
    ->getEntityType('paragraphs_library_item');

  //$entity_definition_update_manager->uninstallEntityType($entity_type);
  $entity_type
    ->set('translatable', TRUE);
  $keys = $entity_type
    ->getKeys();
  $keys['langcode'] = 'langcode';
  $entity_type
    ->set('entity_keys', $keys);

  //$entity_type->setHandlerClass('storage_schema', LibraryItemStorageSchema::class);
  $entity_definition_update_manager
    ->updateEntityType($entity_type);
  $langcode_field = BaseFieldDefinition::create('language')
    ->setLabel(t('Language'))
    ->setDisplayOptions('view', [
    'region' => 'hidden',
  ])
    ->setDisplayOptions('form', [
    'type' => 'language_select',
    'weight' => 2,
  ])
    ->setRevisionable(TRUE)
    ->setTranslatable(TRUE);
  $default_langcode_field = BaseFieldDefinition::create('boolean')
    ->setLabel(t('Default translation'))
    ->setDescription(t('A flag indicating whether this is the default translation.'))
    ->setTranslatable(TRUE)
    ->setRevisionable(TRUE)
    ->setDefaultValue(TRUE);
  $entity_definition_update_manager
    ->installFieldStorageDefinition('langcode', $entity_type
    ->id(), 'paragraphs_library', $langcode_field);
  $entity_definition_update_manager
    ->installFieldStorageDefinition('default_langcode', $entity_type
    ->id(), 'paragraphs_library', $default_langcode_field);
  \Drupal::entityTypeManager()
    ->clearCachedDefinitions();
  foreach ($library_values as $library_value) {
    $library_value['paragraphs'] = [
      'target_id' => $library_value['paragraphs__target_id'],
      'target_revision_id' => $library_value['paragraphs__target_revision_id'],
    ];
    unset($library_value['paragraphs__target_id']);
    unset($library_value['paragraphs__target_revision_id']);
    LibraryItem::create($library_value)
      ->save();
  }
}