-
Update Field Value for All Nodes
I recently added a “Show in Listing” boolean on/off checkbox field to a content type (default value is to be “checked”). There were 133 nodes when I created that field. I needed to update all of those nodes to be “checked”.
Here’s how I updated all of them using entity_metadata_wrapper(). It’s much quicker than any alternative I could think of (feeds, rules, etc.).
1234567891011$nids = db_query('SELECT nid FROM {node} WHERE type = :type', array(':type' => 'blogpost'))->fetchCol();foreach ($nids as $nid) {$node = node_load($nid);if ($node) {$wrapper = entity_metadata_wrapper('node', $node);if (isset($wrapper->field_islisted)) {$wrapper->field_islisted->set(1);$wrapper->save();}}}In this particular case I’m targeting a single content type. I could’ve used a similar query and some slight modifications to set the value on any node whose bundle (content type) supports that field_islisted field.
Lastly, if you have a lot of nodes, you might consider using node_load_multiple() instead of node_load() .
-
Copying Values Between Fields on Thousands of Entities
In a nutshell, I had a List (text) field that I needed to convert to a Text field (so that I wasn’t locked in to specific values anymore). Instead of trying to modify the field to convert it from one type to another, I decided to create a new Text field and populate it with the data from the List field (modifying it a bit first). Here’s the script I used to do this. Admittedly it could be cleaner, more efficient, etc. but it’ll show you a few things, and it got the job done for me.
If you choose to run with
drush scr update_nodes.php
you can leave out the top 3 bootstrap lines.