Last active
November 9, 2022 18:19
-
-
Save pbuyle/51d30e80a17920f6df12 to your computer and use it in GitHub Desktop.
Drupal - Migrate existing field content from language "undefined" to entity language in a single hook_update_N() implementation.
This file contains 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 | |
/** | |
* Migrate existing field content from language "undefined" to entity language. | |
*/ | |
function MODULE_update_N(&$sandbox) { | |
// Number of entities to be processed for each step. | |
$messages = array(); | |
if (!isset($sandbox['fields'])) { | |
// Initialize the array of field to process. | |
$sandbox['fields'] = array_filter(field_info_fields(), function($field_info) {return $field_info['translatable'];}); | |
foreach (array_keys($sandbox['fields']) as $field_name) { | |
$sandbox['fields'][$field_name]['context'] = array('sandbox' => array(), 'finished' => 0); | |
} | |
} | |
// Search for an unfinished field. | |
$field_names = array_keys($sandbox['fields']); | |
$field_name = &reset($field_names); | |
while ($field_name && $sandbox['fields'][$field_name]['context']['finished'] >= 1) { | |
$field_name = &next($field_names); | |
} | |
if ($field_name) { | |
// Process the field. | |
module_load_include('inc', 'entity_translation', 'entity_translation.admin'); | |
entity_translation_translatable_batch(TRUE, $sandbox['fields'][$field_name]['field_name'], TRUE, $sandbox['fields'][$field_name]['context']); | |
$sandbox['#finished'] = array_reduce($sandbox['fields'], function($carry, $item) { | |
return $carry + $item['context']['finished']; | |
}, 0) / count($sandbox['fields']); | |
$message_args = array( | |
'@field_name' => $sandbox['fields'][$field_name]['field_name'], | |
'@progress' => (new NumberFormatter('en_US', NumberFormatter::PERCENT))->format($sandbox['#finished']), | |
'@field_progress' => (new NumberFormatter('en_US', NumberFormatter::PERCENT))->format($sandbox['fields'][$field_name]['context']['finished']) | |
); | |
if ($sandbox['fields'][$field_name]['context']['finished'] >= 1) { | |
$messages[] = format_string('@progress - Done with @field_name.', $message_args); | |
} | |
else { | |
$messages[] = format_string('@progress - Processing @field_name (@field_progress)... ', $message_args); | |
} | |
} | |
else { | |
// No more field to process, we are done. | |
$sandbox['#finished'] = 1; | |
} | |
return implode("\n", $messages); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment