Skip to content

Instantly share code, notes, and snippets.

@welly
Last active January 29, 2024 15:48
Show Gist options
  • Save welly/e60aa594f589640f21ec0eef66d8a934 to your computer and use it in GitHub Desktop.
Save welly/e60aa594f589640f21ec0eef66d8a934 to your computer and use it in GitHub Desktop.
Bulk update nodes to enable automatic URL alias generation
<?php
function mymodule_update_9001(&$sandbox) {
// Initialize variables on the first run.
if (!isset($sandbox['total'])) {
$entity_list = \Drupal::entityQuery('node')
->condition('type', 'my_entity')
->execute();
$langcodes = \Drupal::languageManager()->getLanguages();
$sandbox['langcodes'] = array_keys($langcodes);
$sandbox['total'] = count($entity_list);
$sandbox['current'] = 0;
}
// Batch cycle.
$batch_nids = \Drupal::entityQuery('node')
->condition('type', 'my_entity')
->range($sandbox['current'], 15)
->execute();
foreach ($batch_nids as $nid) {
$my_entity = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
// Loop through all languages.
foreach ($sandbox['langcodes'] as $langcode) {
if ($my_entity->hasTranslation($langcode)) {
$my_entity_translation = $my_entity->getTranslation($langcode);
// Avoid re-saving nodes that don't need to be updated.
if ($my_entity_translation->path->pathauto !== 1) {
$my_entity_translation->path->pathauto = 1;
$my_entity_translation->save();
}
}
}
$sandbox['current']++;
}
if ($sandbox['current'] >= $sandbox['total']) {
$sandbox['#finished'] = 1;
\Drupal::messenger()->addMessage('A total of ' . $sandbox['total'] . ' entities were updated.');
}
else {
$sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);
// Output a message to inform about the ongoing process.
\Drupal::messenger()->addMessage($sandbox['current'] . ' entities were updated out of ' . $sandbox['total']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment