Skip to content

Instantly share code, notes, and snippets.

@johnennewdeeson
Last active January 11, 2017 23:10
Show Gist options
  • Save johnennewdeeson/26a1f0082aa3f5c4dd47 to your computer and use it in GitHub Desktop.
Save johnennewdeeson/26a1f0082aa3f5c4dd47 to your computer and use it in GitHub Desktop.
Drupal move all data from one field to another on the same node programatically.
/**
* Move all data in one field to another.
* In the example below we replace a multi cardinality field (field_old_field)
* with a single cardinality field (field_new_field).
* The data in the first element of the old field becomes the only data in the new field.
*
* @requires entity module
*/
function mymodule_update_7001(&$sandbox) {
if (!isset($sandbox['progress'])) {
$query = new EntityFieldQuery();
$count = $query->entityCondition('entity_type', 'node', '=')
->entityCondition('bundle', 'page')
->count()
->execute();
$sandbox['progress'] = 0;
$sandbox['max'] = $count;
watchdog('mymodule', 'Going to process :count page', array(':count' => $count));
}
$query = new EntityFieldQuery();
$results = $query->entityCondition('entity_type', 'node', '=')
->entityCondition('bundle', 'page')
->range($sandbox['progress'], 10)
->execute();
$node_ids = empty($results['node']) ? array() : array_keys($results['node']);
foreach ($node_ids as $node_id) {
try {
$node_wrapper = entity_metadata_wrapper('node', $node_id);
$node_wrapper->field_new_field->set($node_wrapper->field_old_field[0]->value());
$node_wrapper->save();
}
catch (Exception $e) {
watchdog('mymodule', 'Problem with node @node_id', array('@node_id' => $node_id), WATCHDOG_ERROR);
}
$sandbox['progress']++;
}
watchdog('mymodule', 'Processed :progress / :count page', array(
':progress' => $sandbox['progress'],
':count' => $sandbox['max'],
));
$sandbox['#finished'] = empty($sandbox['max']) || empty($node_ids) ? 1 : ($sandbox['progress'] / $sandbox['max']);
}
@melissamcewen
Copy link

melissamcewen commented May 20, 2016

Thanks for sharing this. How does your sandbox work?

Oh ahaha here is a great explanation http://bleen.net/blog/running-batch-processes-update-hook-bed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment