Skip to content

Instantly share code, notes, and snippets.

@Dropa
Created July 10, 2017 10:39
Show Gist options
  • Save Dropa/aa6bfe3296a25fbb59c1a0812191528a to your computer and use it in GitHub Desktop.
Save Dropa/aa6bfe3296a25fbb59c1a0812191528a to your computer and use it in GitHub Desktop.
<?php
$users = \Drupal::entityQuery('user')
->execute();
$max = count($users);
$pointer = 0;
foreach (array_chunk($users, 100) as $chunk) {
foreach ($chunk as $user_id) {
$pointer++;
$user = \Drupal\user\Entity\User::load($user_id);
foreach ($user->getFieldDefinitions() as $key => $field) {
if (!$field instanceof \Drupal\field\Entity\FieldConfig) {
// Not interested in base fields.
continue;
}
if ($field->getType() != 'entity_reference') {
continue;
}
$need_repair = FALSE;
$valid_keys = [];
$invalid_keys = [];
foreach ($user->get($key) as $key_field) {
if (!$key_field->entity) {
// Missing entity. Update this field from this contact.
$need_repair = TRUE;
$invalid_key = $key_field->target_id;
$invalid_keys[$invalid_key] = $invalid_key;
continue;
}
$valid_key = $key_field->target_id;
$valid_keys[$valid_key] = $valid_key;
}
if ($need_repair) {
$string = implode(" ,", $invalid_keys);
drush_print("Removed references to IDs {$string} from user {$user_id} field {$key}");
//$user->set($key, $valid_keys);
//$user->save();
}
}
}
$status = floor($pointer / $max * 100);
drush_print("Processed $status%");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment