Skip to main content
Custom Form API Elements from Custom Fields
October 22, 2012 |

Some time back, I wrote a blog post entitled Compound fields in Drupal 7 where I discussed how to create custom fields for your content types using Field API. Since then, I've often been asked how to create custom fields for use in forms (using Form API), outside of using those fields in entities such as nodes and taxonomy terms. Assuming you've read that blog post, I'll now show you how to extend an existing custom field into a form element that you can use in any FAPI form.


To extend your field, you'll need to add some additional hooks to your module. It's important to note that you can extend any field into a form element that exists in Drupal, not just something defined by your module. hook_element_info -- This hook tells Drupal about your form element.

[php]1 function dnd_fields_element_info() {
2  return array(
3    'dnd_fields_attribute' => array(
4      '#input' => TRUE,
5      '#tree' => TRUE,
6      '#process' => array('dnd_fields_attribute_process'),
7      '#element_validate' => array('dnd_fields_element_validate'),
8      '#theme' => array('dnd_fields_element'),
9      '#theme_wrappers' => array('form_element'),
10    ),
11  );
12 }[/php]

Process Functions

In hook_element_info, we named a processor function that will define how our new form element should be processed. In this example, we are "faking" a field instance so that we can reuse the field widget defined in hook_field_widget_form (dnd_fields_field_widget_form). If you prefer, you can skip to the next code sample to create a standalone element processor function without relying on what requirements this Field API hook has.

[php]function dnd_fields_attribute_process($element, &$form_state) {
  // Create a dummy field instance just to get the same output from our existing field widget
  $instance = array(
    'field_name' => 'dnd_fields_ability',
    'settings' => array(),
    'widget' => array(
      'type' => 'dnd_fields_ability',

  $form = array();
  $field = array(
    'settings' => array(
      'abilities' => array(),
  $langcode = LANGUAGE_NONE;
  $items = array();
  $delta = 0;
  $form_state['field'] = array(
    'dnd_fields_ability' => array(
      $langcode => array(
        'field' => array(
          'type' => 'dnd_fields_ability',
          'cardinality' => 6,
          'settings' => array(),

  $element = dnd_fields_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);
  return $element;

If you are creating a new form element that does not come from an existing field, you will want this instead:

[php]function dnd_fields_attribute_process($element, &$form_state) {
  $fields = array(
    'ability' => t('Ability'),
    'score' => t('Score'),
    'mod' => t('Modifier'),
    'tempscore' => t('Temp score'),
    'tempmod' => t('Temp modifier'),

  foreach ($fields as $key => $label) {
    $element[$key] = array(
      '#attributes' => array('class' => array('edit-dnd-fields-ability'), 'title' => t('')),
      '#type' => 'textfield',
      '#size' => 3,
      '#maxlength' => 3,
      '#title' => $label,
      '#default_value' => NULL,
      '#attached' => array(
        'css' => array(drupal_get_path('module', 'dnd_fields') . '/dnd_fields.3x.css'),
        'js' => array(drupal_get_path('module', 'dnd_fields') . '/dnd_fields.3x.js'),
      '#prefix' => '<div class="dnd-fields-ability-field dnd-fields-ability-' . $key . '-field">',
      '#suffix' => '</div>',

  return $element;

Technically, we're done. You now have a form element that you can define in any Form API code. For example:

[php]function dnd_character_test_form($form, &$form_state) {
  $form = array();
  $form['test'] = array(
    '#type' => 'dnd_fields_attribute',
    '#title' => t('Attribute fields'),
    '#description' => t('Provide a description here.'),
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  return $form;

Themeing your Element

The cool thing with your new form element is that you can theme it, even though this is not strictly neccessary, since the widget defined in the field will handle most of this for you. So feel free to skip this step if you're already happy with the Field API widget that you have. The following code sample displays a generic form output, since the field that we defined is really just a special case of the 'textfield' form element type. However, you can feel free to get fancy here, and display literally any HTML output you want. Also of note is that this is just like any other theme function in Drupal. You can refine this more using preprocess theme functions and .tpl.php files to theme your form element even more. However, for this example, I'm going to keep it simple.

[php]function theme_dnd_fields_element($variables) {
  $element = $variables['element'];

  $attributes = array();
  if (isset($element['#id'])) {
    $attributes['id'] = $element['#id'];
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] = (array) $element['#attributes']['class'];
  $attributes['class'][] = 'dnd-fields-ability';

  // This wrapper is required to apply JS behaviors and CSS styling.
  $output = '';
  $output .= '<div' . drupal_attributes($attributes) . '>';
  $output .= drupal_render_children($element);
  $output .= '</div>';
  return $output;[/php]

Tobby is a software development professional with over two decades of experience architecting and implementing content management systems, APIs, and other enterprise frameworks. Tobby provides technical oversight across many of Phase2’s projects, ensuring best practices and efficient workflows are followed, and shares his years of experience to help clients find the complete solution to their problems.

Jump back to top