Module Development

Defining a Field's Schema for Database Storage for Drupal 7

Check your version

This tutorial covers a topic in Drupal 7 which may or may not be the version you're using. We're keeping this tutorial online as a courtesy to users of Drupal 7, but we consider it archived.

Alternate resources

Sprout Video

Before we can actually get our field to store data for us we need to define what the data that we're going to store looks like. The Field API does this with hook_field_schema(), which uses a very similar syntax to what is used by the hook_schema() that modules can use to define database tables. In this particular case though we're only defining what the column, or columns, that store our specific data will be and allowing the Field Storage API to decide what the structure of the created table, or tables, should be. This allows our field to remain mostly storage system agnostic and frees us from having to worry about things like how the stored field data is connected back to the entity that it belongs to, or how to format our table for proper handling of revision data or translations.

Example hook_field_schema() implemenatation.


/**
 * Implements hook_field_schema().
 */
function rgb_field_schema($field) {
  $columns = array(
    'rgb' => array(
      'type' => 'varchar',
      'length' => 6,
      'not null' => FALSE,
    ),
    'label' => array(
      'type' => 'varchar',
      'length' => 128,
      'not null' => FALSE,
    ),
  );

  $indexes = array(
    'rgb' => array('rgb'),
  );

  return array(
    'columns' => $columns,
    'indexes' => $indexes,
  );
}