Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Drupal update hook to copy a field into another
/**
* Implements hook_update_N().
*
* Copies title for legacy_content type.
*/
function rs_update_7100(&$sandbox) {
if (!isset($sandbox['max'])) {
$query = db_select('node', 'n');
$query->addExpression('COUNT(*)', 'count');
$query->condition('n.type', 'legacy_content');
$sandbox['max'] = $query->execute()->fetchField();
$sandbox['current_position'] = 0;
}
if ($sandbox['max'] > 0) {
$limit = 10;
$nids = db_select('node', 'n')
->fields('n', array('nid'))
->condition('n.type', 'legacy_content')
->orderBy('n.nid')
->range($sandbox['current_position'], $limit)
->execute()
->fetchCol();
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
$node->field_title[$node->language][0]['value'] = $node->title;
node_save($node);
}
$sandbox['current_position'] += $limit;
$sandbox['#finished'] = $sandbox['current_position'] / $sandbox['max'];
}
else {
$sandbox['#finished'] = 1;
}
if ($sandbox['#finished'] >= 1) {
drupal_set_installed_schema_version('rs', 7100);
return format_plural($sandbox['max'], '1 node updated', '@count nodes updated');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment