Skip to content

Instantly share code, notes, and snippets.

@wbobeirne
Created May 23, 2013 15:16
Show Gist options
  • Save wbobeirne/5636835 to your computer and use it in GitHub Desktop.
Save wbobeirne/5636835 to your computer and use it in GitHub Desktop.
<?php
/**
* Copy the data from one field to another, and delete the old field.
*/
function merge_fields($old_field, $new_field, $entity_type = '', $bundle = '') {
$prefixes = array(
'field_data_',
'field_revision_',
);
foreach ($prefixes as $prefix) {
$query = db_select($prefix . $old_field, 'old_field')
->fields('old_field');
if (!empty($entity_type) && !empty($bundle)) {
$query->condition('old_field.entity_type', $entity_type);
$query->condition('old_field.bundle', $bundle);
}
$results = $query->execute();
while ($row = $results->fetchAssoc()) {
// Replace columns that are prefixed with field name.
foreach ($row as $idx => $value) {
if (strstr($idx, $old_field)) {
$row[str_replace($old_field, $new_field, $idx)] = $value;
unset($row[$idx]);
}
}
db_insert($prefix . $new_field)
->fields($row)
->execute();
}
}
if (!empty($entity_type) && !empty($bundle)) {
field_delete_instance(array(
'field_name' => $old_field,
'entity_type' => $entity_type,
'bundle' => $bundle,
));
field_create_instance(array(
'field_name' => $new_field,
'entity_type' => $entity_type,
'bundle' => $bundle,
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment