Field Collection Import/Export in Drupal 7

The Field Collection module has become essential to our work with Drupal, allowing us to create “compound” fields – fields within fields. When using the Node Export module to export nodes from one Drupal instance to another, Node Export doesn’t provide a way to transfer the field collection data. It turns out that it’s easy to programmatically import and export field collection instances though. This will export all the field collections on a site and store them in an array:

  $rows = db_query("SELECT * FROM field_collection_item;")->fetchAll();

  $export = $all_ids = array();

  foreach($rows as $row){
    $all_ids[] = $row->item_id;
  }

  $items = entity_load("field_collection_item", $all_ids);

  foreach($items as $item){
    $export[] = $item->export();
  }

This is thanks to the field collection entity’s controller class EntityAPIController implementing a handy export() method.

Then to import a field collection exported to $export_str:

  $con = new EntityAPIController("field_collection_item");
  $entity = $con->import($export_str);
  $con->save($entity);

The exported JSON contains an item_id. If you unset this the collection will be saved with a new item_id (generally a good idea) but there are some circumstances where you might want to import the field collection with its original ID (this will maintain the references to the field collections host but be careful!)

Importing and exporting is never fun with Drupal but the above code should help with any tasks (in my case populating a site with test data needed by Selenium tests) that require field collections to be moved between sites.

Leave a Reply

Spam protection by WP Captcha-Free

Posted