Skip to main content

Custom Form API Elements from Custom Fields

Tobby Hagler | Director, Engineering

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.

Hooks

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.

function dnd_fields_element_info() {
  return array(
    'dnd_fields_attribute' => array(
      '#input' => TRUE,
      '#tree' => TRUE,
      '#process' => array('dnd_fields_attribute_process'),
      '#element_validate' => array('dnd_fields_element_validate'),
      '#theme' => array('dnd_fields_element'),
      '#theme_wrappers' => array('form_element'),
    ),
  );
}

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.

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:

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:

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;
}

Theming 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.

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;
}

Recommended Next
Development
A Developer's Guide For Contributing To Drupal
Black pixels on a grey background
Development
3 Steps to a Smooth Salesforce Integration
Black pixels on a grey background
Development
Drupal 8 End of Life: What You Need To Know
Woman working on a laptop
Jump back to top