Last active
March 1, 2021 21:43
-
-
Save gheydon/da3abc33697bd3fa72b91abc8716ac54 to your computer and use it in GitHub Desktop.
Reset the auto generated path of an entity and regenerate.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Drupal\pathauto\PathautoState; | |
/** | |
* Regenerate FAQ category URL's. | |
*/ | |
function example_post_update_regenerate_node_urls(&$sandbox) { | |
return example_regenerate_urls($sandbox, 'taxonomy_term', ['faq_category']); | |
} | |
/** | |
* Generate URL for an entity type and a list of bundles. | |
*/ | |
function example_regenerate_urls(&$sandbox, $entity_type_id, $bundles) { | |
$chunk_size = 10; | |
/** @var \Drupal\pathauto\PathautoGenerator $pathautoGenerator */ | |
$pathautoGenerator = \Drupal::service('pathauto.generator'); | |
$entity_type_manager = \Drupal::entityTypeManager(); | |
$entity_type = $entity_type_manager->getDefinition($entity_type_id); | |
$storage_manager = $entity_type_manager->getStorage($entity_type_id); | |
$id_field = $entity_type->getKey('id'); | |
if (empty($sandbox['entity_chunks'])) { | |
$select = \Drupal::database()->select($entity_type->getBaseTable(), 'base_table'); | |
$select->addField('base_table', $id_field, $id_field . '_1'); | |
$select->addField('base_table', $id_field); | |
$select->condition('base_table.' . $entity_type->getKey('bundle'), $bundles, 'IN'); | |
$ids = $select->execute()->fetchAllKeyed(); | |
$sandbox['total'] = count($ids); | |
$sandbox['entity_chunks'] = array_chunk($ids, $chunk_size); | |
} | |
$ids = array_pop($sandbox['entity_chunks']); | |
foreach ($storage_manager->loadMultiple($ids) as $entity) { | |
$entity->path->pathauto = PathautoState::CREATE; | |
$pathautoGenerator->updateEntityAlias($entity, 'bulkupdate', [ | |
'message' => FALSE, | |
'force' => TRUE, | |
]); | |
\Drupal::keyValue('pathauto_state.' . $entity->getEntityTypeId()) | |
->set(PathautoState::getPathautoStateKey($entity->id()), PathautoState::CREATE); | |
} | |
$sandbox['#finished'] = empty($sandbox['entity_chunks']) ? 1 : | |
($sandbox['total'] - (count($sandbox['entity_chunks']) * $chunk_size)) / | |
$sandbox['total']; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment