Drupal 7: Bulk Exporting Entity Fields

Posted under: 

If you've ever needed to export all of the fields out of a Drupal Entity, this might help.

  1. Install the devel module
  2. Find the machine name of the entity to export, page, article, etc.
  3. Find the entity type: This could be: node, taxonomy_term, field_collection_item, user, or some custom entity.
  4. Paste the attached code into one of Devel's "Execute PHP Code" text areas. (Exported code in text file)
  5. Change the first two variables to the values you've identified.
  6. Execute.

$bundle_name = 'page'; // change to specific node type, taxonomy name, or user.
$entity_type = 'node'; // change to match entity type (node, taxonomy_term, field_collection_item, user)
$instances = field_info_instances($entity_type, $bundle_name);
$export_prefix = ''; // Optional way to prefix exported field arrays.

// Fields to drop from field definition code.
$block_definition = array(
  'field_optional_name', // Optional exclude fields from Definition array in case they are defined in alternate entity.

$field_output = '';
$instance_output = '';

foreach ($instances as $instance) {
  $field_name = $instance['field_name'];
  if ($field_name != 'body') {
    $info_config = field_info_field($field_name);
    $info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
    unset($info_instance['id'], $info_instance['field_id']);
    include_once DRUPAL_ROOT . '/includes/utility.inc';

    if (in_array($field_name, $block_definition)) {
      $field_output = $field_output;
    else {
      $field_output .= "// FIELD: " . $field_name . ".\n'" . $export_prefix . $field_name . "' => " . drupal_var_export($info_config) . ",\n\n";
    $instance_output .= "// INSTANCE: " . $field_name . ".\n'" . $export_prefix . $field_name . "' => " . drupal_var_export($info_instance) . ",\n\n";

drupal_set_message("<textarea rows="30" style="\">" . $field_output . '</textarea>');
drupal_set_message("<textarea rows="30" style="\">" . $instance_output . '</textarea>');

The exported code will be displayed in two TextArea fields for easily cutting and pasting to where ever you need the code.

If you are exporting multiple entities, add a unique prefix to the $export_prefix variable. This will allow you to merge the supplied arrays without duplicating array keys.

If you're reusing fields across multiple entities, place the field names in $block_definitions array in all but the original source entity. This will exclude the field definition from being exported multiple times. Remember to leave that array empty for the original source of the field, or you won't get the field definition where you need it.

If you're exporting User fields, both the Entity type and the bundle name are "user".

This is a modified version of something I found online a few years ago. If someone sees the original version someplace, please let me know. I've been meaning to thank them, but haven't found the source.

Add comment