Skip to content

Instantly share code, notes, and snippets.

@jmolivas
Last active November 9, 2017 20:25
Show Gist options
  • Save jmolivas/674b1d67100e8c253a42526aa179ffdf to your computer and use it in GitHub Desktop.
Save jmolivas/674b1d67100e8c253a42526aa179ffdf to your computer and use it in GitHub Desktop.
Update all of the instances of a field in a Drupal 8 database
<?php
function _update_table_field($fieldName, $valueMapping) {
$schema = \Drupal::database()->schema();
$tables = $schema->findTables('%');
foreach ($tables as $table) {
if ($schema->fieldExists($table, $fieldName)) {
foreach ($valueMapping as $originalValue => $newValue) {
echo sprintf(
'Updating table %s and field %s from %s to %s',
$table,
$fieldName,
$originalValue,
$newValue
). PHP_EOL;
\Drupal::database()
->update($table)
->fields([$fieldName => $newValue])
->condition($fieldName, $originalValue)
->execute();
}
}
}
}
function module_name_update_N(&$sandbox) {
$fieldName = 'langcode';
$valueMapping = [
'en' => 'und',
'en-GB' => 'en-gb'
];
_update_table_field($fieldName, $valueMapping);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment