You are here

function fillpdf_update_8103 in FillPDF 8.4

Same name and namespace in other branches
  1. 5.0.x fillpdf.install \fillpdf_update_8103()

Use file fields instead of entity_reference fields for referring to files.

File

./fillpdf.install, line 46
Install functions for FillPDF.

Code

function fillpdf_update_8103() {
  $edum = \Drupal::entityDefinitionUpdateManager();
  $em = \Drupal::entityTypeManager();
  $db = \Drupal::database();
  $form_file_def = BaseFieldDefinition::create('file')
    ->setLabel(t('The associated managed file.'))
    ->setDescription(t('The associated managed file.'))
    ->setName('file')
    ->setProvider('fillpdf_form')
    ->setTargetBundle(NULL)
    ->setTargetEntityTypeId('fillpdf_form');
  $fc_file_def = BaseFieldDefinition::create('file')
    ->setLabel(t('The associated managed file.'))
    ->setDescription(t('The associated managed file.'))
    ->setName('file')
    ->setProvider('fillpdf_file_context')
    ->setTargetBundle(NULL)
    ->setTargetEntityTypeId('fillpdf_file_context');

  // Save existing data.
  $form_files = $db
    ->select('fillpdf_forms', 'ff')
    ->fields('ff', [
    'fid',
    'file',
  ])
    ->execute()
    ->fetchAllKeyed();
  $fc_files = $db
    ->select('fillpdf_file_context', 'fc')
    ->fields('fc', [
    'id',
    'file',
  ])
    ->execute()
    ->fetchAllKeyed();

  // Remove data from the storage.
  $db
    ->update('fillpdf_forms')
    ->fields([
    'file' => NULL,
  ])
    ->execute();
  $db
    ->update('fillpdf_file_context')
    ->fields([
    'file' => NULL,
  ])
    ->execute();

  // Now install the new field definitions.
  $edum
    ->updateFieldStorageDefinition($form_file_def);
  $edum
    ->updateFieldStorageDefinition($fc_file_def);
  foreach ($form_files as $entity_id => $fillpdf_form_file) {

    /** @var ContentEntityInterface $entity */
    $entity = $em
      ->getStorage('fillpdf_form')
      ->load($entity_id);
    $entity->file->target_id = $fillpdf_form_file;
    $entity
      ->save();
  }
  foreach ($fc_files as $entity_id => $ffcf) {

    /** @var ContentEntityInterface $entity */
    $entity = $em
      ->getStorage('fillpdf_file_context')
      ->load($entity_id);
    $entity->file->target_id = $ffcf;
    $entity
      ->save();
  }
}