You are here

function paragraphs_update_8018 in Paragraphs 8

Make the parent fields revisionable.

File

./paragraphs.install, line 352
Installation hooks for Paragraphs module.

Code

function paragraphs_update_8018(&$sandbox) {
  $database = \Drupal::database();

  // Initialize some variables during the first pass through.
  if (!isset($sandbox['total'])) {

    // Add the parent fields to the revision data table.
    foreach ([
      'parent_id',
      'parent_type',
      'parent_field_name',
    ] as $field_name) {
      $column_schema = [
        'type' => 'varchar_ascii',
        'length' => $field_name == 'parent_id' ? 255 : 32,
        'binary' => FALSE,
        'not null' => FALSE,
      ];

      // Create fields if they don't already exist.
      if (!$database
        ->schema()
        ->fieldExists('paragraphs_item_revision_field_data', $field_name)) {
        $database
          ->schema()
          ->addField('paragraphs_item_revision_field_data', $field_name, $column_schema);
      }
    }

    // Get all paragraphs to update.
    $paragraphs = \Drupal::database()
      ->select('paragraphs_item_field_data', 'p')
      ->countQuery()
      ->execute()
      ->fetchField(0);
    $sandbox['total'] = $paragraphs;
    $sandbox['current'] = 0;
  }

  // Do not continue if no paragraphs are found.
  if (empty($sandbox['total'])) {
    $sandbox['#finished'] = 1;
    return t('No Paragraphs to be processed.');
  }
  $paragraphs_per_batch = 50;
  $query = $database
    ->select('paragraphs_item_field_data', 'p');
  $query
    ->fields('p', [
    'id',
    'parent_id',
    'parent_type',
    'parent_field_name',
  ]);
  $query
    ->range($sandbox['current'], $paragraphs_per_batch);
  $result = $query
    ->execute();
  foreach ($result as $row) {
    $database
      ->update('paragraphs_item_revision_field_data')
      ->fields([
      'parent_id' => $row->parent_id,
      'parent_type' => $row->parent_type,
      'parent_field_name' => $row->parent_field_name,
    ])
      ->condition('id', $row->id)
      ->execute();
    $sandbox['current']++;
  }
  $sandbox['#finished'] = $sandbox['current'] / $sandbox['total'];
  return t('@count Paragraphs processed.', [
    '@count' => $sandbox['current'],
  ]);
}