Skip to content

Instantly share code, notes, and snippets.

@init90
Created October 23, 2017 14:02
Show Gist options
  • Select an option

  • Save init90/77492c1c355851b9825977139cd7c026 to your computer and use it in GitHub Desktop.

Select an option

Save init90/77492c1c355851b9825977139cd7c026 to your computer and use it in GitHub Desktop.
Drupal 8, allow run hook update after module install and example how run batch update in drupal 8.
<?php
use Drupal\Core\Database\Database;
use Drupal\group_revision\GroupRevisionTrait;
/**
* Implements hook_install().
*/
function group_revision_install() {
// Update entity fields.
\Drupal::service('entity.definition_update_manager')->applyUpdates();
// Allow run update after module install.
drupal_set_installed_schema_version('group_revision', 8000);
}
/**
* Create revision for all flats and added revision to entity expense_item.
*/
function group_revision_update_8001(&$sandbox) {
if (!isset($sandbox['progress'])) {
$flats_ids = \Drupal::entityQuery('group')->condition('type', 'butas')->execute();
$sandbox['group_manager'] = \Drupal::entityTypeManager()->getStorage('group');
$sandbox['ids'] = $flats_ids;
$sandbox['max'] = count($flats_ids);
$sandbox['progress'] = 0;
}
$current_flats_ids = array_slice($sandbox['ids'], $sandbox['progress'], 25);
foreach ($sandbox['group_manager']->loadMultiple($current_flats_ids) as $flat) {
$revision = GroupRevisionTrait::createGroupRevision($flat);
GroupRevisionTrait::setRevisionToGroup($flat, $revision);
// Set flat revision to expense items.
Database::getConnection('default')
->update('expense_item')
->fields(['flat_revision' => $revision->id()])
->condition('flat_id', $flat->id())
->execute();
$sandbox['progress']++;
}
$sandbox['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);
return t('Created revision for @progress flats out of @max.', ['@progress' => $sandbox['progress'], '@max' => $sandbox['max']]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment