Drupal - Bulk field update?
You can use EntityFieldQuery
to retrieve a list of nodes, then update the node's fields with node_save()
:
$lang = LANGUAGE_NONE; // Replace with ISO639-2 code if localizing
$node_type = 'page'; // Machine name of the content type
$query = new EntityFieldQuery;
$result = $query
->entityCondition('entity_type', 'node')
->propertyCondition('type', $node_type)
->execute();
if (!empty($result['node'])) {
$nodes = entity_load('node', array_keys($result['node']));
foreach($nodes as $node) {
// Replace field_foo with the machine name of the field to update.
// - 0 refers to specific value within the field array, for when the field contains
// multiple values. If the field only has one value, it should be 0.
$node->field_foo[$lang][0]['value'] = 'New Value';
node_save($node);
}
}
If this is a one-off operation, you can use the Devel module's Execute PHP function to run the above: otherwise, you can create a simple custom module.
I would use Views Bulk Operations and use the "Execute Arbitrary PHP Script" to do essentially the items above, but you don't have to do all the extra code, just the little snippet that does what you want (like $object->field_foo['und'][0]['value'] = 'some_value'
)
If you want only to update field with some value, then the more performant alternative to accepted answer is this:
$lang = LANGUAGE_NONE; // Replace with ISO639-2 code if localizing
$node_type = 'page'; // Machine name of the content type
$query = new EntityFieldQuery;
$result = $query
->entityCondition('entity_type', 'node')
->propertyCondition('type', $node_type)
->execute();
if (!empty($result['node'])) {
$nodes = entity_load('node', array_keys($result['node']));
foreach($nodes as $node) {
// Replace field_foo with the machine name of the field to update.
// - 0 refers to specific within the field array, for when the field contains
// multiple values. If the field only has one value, it should be 0.
$node->field_foo[$lang][0]['value'] = 'New Value';
field_attach_presave('node', $node);
field_attach_update('node', $node);
}
}
The difference is in using directly field_attach_presave
and field_attach_update
functions, which update correctly only node field and skip the rest of node saving process. This has an impact that no node presave/save hooks will be called, "changed" date will not be updated to current date etc. According your use case it may be better as using whole node_save() process.