Last active
November 9, 2017 20:25
-
-
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
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 | |
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