Module Development

Creating Field Widgets For Collecting User Input for Drupal 7

This page is archived

We're keeping this page up as a courtesy to folks who may need to refer to old instructions. We don't plan to update this page.

Alternate resources

Sprout Video

The term widget refers to the form element, or elements, that are presented to the user when they are entering data for a field. For example, the file upload field on the Article content type is the widget for the image field attached to that content type. When a field instance is attached to a bundle and an admin is creating or editing an entity of that bundle type the Field Attach API calls out to each individual field and asks it for the widget it would like to use to collect data. Adding a widget for a custom field type is a combination of implementing hook_field_widget_info() and hook_field_widget_form().

Examples:


/**
 * Implements hook_field_widget_info().
 */
function rgb_field_widget_info() {
  return array(
    'rgb_textfield' => array(
      'label' => t('RGB Textfields'),
      'field types' => array('rgb_color'),
    ),
  );
}

/**
 * Implements hook_field_widget_form().
 */
function rgb_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  if ($field['cardinality'] == 1) {
    $element['#type'] = 'fieldset';
  }

  $element['rgb'] = array(
    '#type' => 'textfield',
    '#field_prefix' => t('RGB: #'),
    '#size' => 6,
    '#default_value' => isset($items[$delta]['rgb']) ? $items[$delta]['rgb'] : '',
  );

  $element['label'] = array(
    '#type' => 'textfield',
    '#field_prefix' => t('Color name: '),
    '#default_value' => isset($items[$delta]['label']) ? $items[$delta]['label'] : '',
  );

  return $element;
}

Additional resources

Legacy Module Development