Using VBO to copy and paste fields inside a node, using field collections and node/entity reference

You can create VBO actions that can do something for you but for a quick solution and one time actions you can use "Execute arbitrary PHP script" and there you have $entity and $context object that you get one per each line of yout VBO view.

So what I did was copy some text and node reference fields to field collections fields, that have text and entity reference in them. This took a little bit more coding and clever thinking but with google and some help of this page
https://drupal.org/node/1842304

I managed to wrap entity in this "entity_metadata_wrapper" and loop through the default fields that have multi array and set fields collection, even entity reference field wasn't a problem with this wrapper as you can see from code below.


//This is just some of my internal calculation for plain text field
$entity->field_savings['und'][0]['value'] = (($entity->field_field_price_2['und'][0]['value']-$entity->field_field_price_1['und'][0]['value'])/$entity->field_field_price_2['und'][0]['value'])*100;

//Here is the code for adding data to collection field
for ($i = 0; $i field_examples_of_price['und']); $i++) {
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_prices_all')); 
$field_collection_item->setHostEntity('node', $entity); 
$fc_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);
$fc_wrapper->field_dentist->set($entity->field_examples_of_price['und'][$i]['nid']);
$fc_wrapper->field_price->set($entity->field_field_price_1['und'][$i]['value']);
$fc_wrapper->save(true);
}
node_save($entity);

In the end we need to also save this entity in VBO action so that is what last code line does and it works. Everything I need is copied.