Adding and reusing a field

Last updated on
26 April 2017

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

Let's begin with creating a last name field. We will add this to users and to the 'picture' node type so that it's possible to put names on them even if the author is not a user.

Our field type will be text. This will be stored in SQL (which is the default):

$field = array(
  // It is strongly advised to prefix the field name with the name of the module 
  // that defines it, to avoid name clashes. Fields created through Field UI are
  // prefixed with 'field_'
  'field_name' => 'mymodule_lastname',
  'type' => 'text',
  'cardinality' => 1, // Not required, as is default. Number of values field can hold. 
);
field_create_field($field);

Users will use common HTML text input fields to enter the data -- this is called a widget. We will format these as Plain text -- we do not need HTML tags in there.

$instance = array(
  'field_name' => 'mymodule_lastname',
  'entity_type' => 'user',
  'bundle' => 'user',
  'label' => t('Last name'),
  'description' => t('You can enter your last name here.'),
  'widget' => array(
    'type' => 'text_textfield',
    'weight' => 10,
  ),
);
field_create_instance($instance);

Now to attach the same field to another bundle (here, node type 'picture'), that's very easy:

$instance['entity_type'] = 'node';
$instance['bundle'] = 'picture';
field_create_instance($instance);

An example of a select field:

$field = array(
  'field_name' => 'name_of_field',
  'type' => 'list_text',
  'settings' => array(
    'allowed_values' => array(
      'key_1' => t('Value 1'),
      'key_2' => t('Value 2'),
      'key_3' => t('Value 3'),
    ),
  ),
);
field_create_field($field);

$instance = array(
  'field_name' => 'name_of_field',
  'label' => t('The label'),
  'entity_type' => 'the_entity_type',
  'bundle' => 'the_bundle',
  'widget' => array(
    'type' => 'options_select',
  ),
);

field_create_instance($instance);

This code is generally placed in the .install file for a module.

Help improve this page

Page status: No known problems

You can: