Creating exportable field definitions in Drupal 7

There are times when we would want to create similar data structures across multiple drupal sites for common functionalities. Although this can be done using features but when the effort involves one time exercise and involves just few fields to be exported, using custom code for creating export definitions for importing in the other site can be a simpler alternative.

If you want export a field definition, you can use the handy field_info_field and field_info_instance functions. Taking our example above, here's how you would call these two functions:

<?php
$field_data
= field_info_field('field_article_image');
$instance_data = field_info_instance('node', 'field_article_image', 'article');
?>

Now that the field and instance definitions is present, to create them in your script executing them for importing requires executing 2 handy Drupal 7 APIs, field_create_field and field_create_instance. Just pass in your field definitions, and you're done.

<?php
field_create_field
($field_data);
field_create_instance($instance_data);
?>

After you've created your fields using the Field UI, navigate to /devel/php (this requires the must-have Devel module) for creating the exportable definitions.
The following script creates exportable field definitions for a field_employee_code field under profile2 entity called staff_profile. Similar structure for profile2 with staff_profile bundle name should exist in the destination site should exist for the import to work.

<?php
$entity_type
= 'profile2';
$field_name = 'field_employee_code';
$bundle_name = 'staff_profile';

$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['id'], $info_instance['field_id']);
include_once
DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style="width: 100%;">" . $output . '</textarea>');
?>

--
Sources:
http://steindom.com/articles/exporting-and-creating-field-definitions-dr...
http://api.drupal.org/api/drupal/modules--field--field.module/group/field/7