/**
* Replaces all "ABCD" strings with "WXYZ" strings on text fields in all nodes.
*/
function mymodule_update_7100(&$sandbox) {
// Set our $sandbox, which will stay persistent in multiple batch processes.
if (!isset($sandbox['total'])) {
// Find all nodes having 'ABCD' in a text field
// UserUse your favorite method here, for the sake of this example I use EFQ.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->propertyCondition('bundle', 'YOUR_CONTENT_TYPE');
$query->fieldCondition('my_text_field', '%ABCD%', 'like');
$result = $query->execute();
// Put the node ids into the $sandbox
$sandbox['nids'] = array_keys($result['node']);
$sandbox['total'] = count($sandbox['nids']);
// Set batch size to a number of nodes your server can process in a single
// request. If you still get timeouts, try to reduce this number.
$sandbox['batch_size'] = 10;
$sandbox['current'] = 0;
}
else {
// The sandbox is set, so we can process the nodes in batches. We load only
// that much of nodes set in the $sandbox['batch_size']
$offset = $sandbox['current'] * $sandbox['batch_size'];
$current_nids = array_slice($sandbox['nids'], $offset, $sandbox['batch_size']);
$nodes = node_load_multiple($current_nids);
foreach ($nodes as $node) {
// Change the text value here and save the node.
// Again use your favorite method here. For the sake of this example, I
// change the value directly on the $node object and save the $node.
$text = $node->my_text_field['und'][0]['value'];
$text = str_replace('ABCD', 'WXYZ', $text);
$node->my_text_field['und'][0]['value'] = $text;
node_save($node);
}
}
// Check the progress and set $sandbox['#finished'] to 1 once all nodes are
// processed.
$progress = $sandbox['current'] * $sandbox['batch_size'] / $sandbox['total'];
$sandbox['#finished'] = $progress > 1 ? 1 : $progress;
}
Put above script in an .install
-file of a custom module. You should adjust the name of the function. Please see the documentation of the hookhook_update_N()
if you are not familiar with update scripts.
Then, you run the update.php
or use drush command drush updb
. This update script will be called as many time as all the nodes are processed which are set in the first part of the if
statement. On the first call, it will just find the nodes and put the node ids in the $sandbox
. On the consequent calls, it will load the nodes in batches of 10 and process them.