Export base field and instance for use in Drupal 7 install

The following snippet used inside devel/php to export field base and instance settings.

It exports the base field definition, adds a wrapper to make sure the field does not yet exist.

It also exports the field instance settings, even allowing to select extra bundles to add the field to.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$entity_type = 'node';
$field_name = 'field_body';
$bundle_name = 'page';
$extra_bundles = array('article');

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);

unset($info_config['id']);
unset($info_instance['field_id']);
unset($info_instance['id']);

include_once DRUPAL_ROOT . '/includes/utility.inc';

$output = '';
$output .= "if (!field_info_field('$field_name')) {\n";
$output .= " field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "}\n\n";

array_unshift($extra_bundles, $bundle_name);

$output .= "\$extra_bundles = " . drupal_var_export($extra_bundles) . ";\n";
$output .= "\$instances = field_info_instances();\n";
$output .= "foreach (\$extra_bundles as \$bundle) {\n";
$output .= " if (empty(\$instances['$entity_type'][\$bundle]['$field_name'])) {\n";
$output .= " field_create_instance(";
$output .= str_replace("'bundle' => '$bundle_name',", "'bundle' => \$bundle,", drupal_var_export($info_instance));
$output .= " );\n";
$output .= " }\n";
$output .= "}\n";


drupal_set_message("<textarea rows=60 cols=120>" . $output . '</textarea>');