You are here

function salesforce_mapping_update_8001 in Salesforce Suite 8.3

Same name and namespace in other branches
  1. 8.4 modules/salesforce_mapping/salesforce_mapping.install \salesforce_mapping_update_8001()
  2. 5.0.x modules/salesforce_mapping/salesforce_mapping.install \salesforce_mapping_update_8001()

Copy entity_id-entity_type_id data into new mapped_entity field.

File

modules/salesforce_mapping/salesforce_mapping.install, line 32
Install file.

Code

function salesforce_mapping_update_8001(&$sandbox) {
  if (!\Drupal::moduleHandler()
    ->moduleExists('dynamic_entity_reference')) {
    throw new \Exception('Please enable new dependency dynamic_entity_reference before continuing.');
  }
  if (!\Drupal::database()
    ->schema()
    ->fieldExists('salesforce_mapped_object', 'drupal_entity__target_id')) {
    throw new \Exception('Refused to run ' . __FUNCTION__ . ' with pending entity definition updates. Please run `entup` first.');
  }
  if (empty($sandbox['progress'])) {
    $sandbox['progress'] = 0;
    $sandbox['current_id'] = 0;
    $sandbox['max'] = db_query("SELECT count(*) FROM salesforce_mapped_object")
      ->fetchField();
    if (empty($sandbox['max'])) {
      $sandbox['#finished'] = 1;
      return t('No mapped objects to update.');
    }
  }

  // Have to go directly to the database for the entity values because they've
  // been removed from baseFieldDefinitions, therefore they don't get attached
  // to the entity on load.
  $mapped_objects = db_query("SELECT id, entity_type_id, entity_id FROM salesforce_mapped_object WHERE id > {$sandbox['current_id']} ORDER BY id ASC LIMIT 3");
  foreach ($mapped_objects as $mapped_object_data) {
    $sandbox['current_id'] = $mapped_object_data->id;
    $sandbox['progress']++;
    $mapped_object = \Drupal::entityTypeManager()
      ->getStorage('salesforce_mapped_object')
      ->load($mapped_object_data->id);
    $mapped_object->drupal_entity
      ->setValue([
      'target_type' => $mapped_object_data->entity_type_id,
      'target_id' => $mapped_object_data->entity_id,
    ]);
    $mapped_object
      ->save();
  }
  $sandbox['#finished'] = empty($sandbox['max']) ? 1 : $sandbox['progress'] / $sandbox['max'];
  if ($sandbox['#finished'] >= 1) {
    return t('Mapped object update complete.');
  }
  return t('Updated !n of !max mapped objects.', [
    '!n' => $sandbox['progress'],
    '!max' => $sandbox['max'],
  ]);
}