Populate a term reference field with data from another

We had added a new term reference field to one of our content types, but it already had an term reference field in place, and had data in it. We needed to populate the new term reference field with the data from the old field, so that we could then delete the old field. 

Had this been a text field, it would have been easy to achieve this using Views, Admin Views (optional), Views Bulk Operations, and Token. Using VBO with "Modify Entity Values" you could then paste a token in the desired text field, and run this on whichever nodes you want - in bulk. Admin Views is a handy way of improving the /admin/content overview, enhancing it with content type and keyword filters with Ajaxy goodness.

Term reference fields don't accept text or tokens that way. In that case we can use VBO's "Execute Arbitrary PHP Script" option, using the following code. 

[This is for Drupal 7]

 

$node = node_load($entity->nid); 
foreach($node->taxonomy_vocabulary_7[LANGUAGE_NONE] as $tid){ 
  $node->field_campus[LANGUAGE_NONE][0]['tid'] = $tid; 
} 
node_save($node);

 

Since VBO runs this on one node at a time, in bulk, node_load is still decently performant. If you were to do something like this in custom code - without VBO - it would be better to use entity_load() along with entity_save() for some performance gains. Using the above code I was able to get the new field populated with VBO in a matter of minutes, as opposed to manually editing 150 nodes, or doing this some other way (custom SQL query, custom module, etc).

Tags: 
Blog categories: