Module Development

Validating and Saving Field Data 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 our field can save user provided data we need to use hook_field_validate() and hook_field_is_empty() to perform validation on field data. In certain context values like 0, FALSE, and NULL can all be a valid value. In fact, even a blank space could be valid input for a field. As such, it's not possible for Drupal to know what constitutes an empty state for a field without a little extra help. The same is true for checking if the value of a field is valid.

Examples:


/**
 * Implementation of hook_field_is_empty().
 */
function rgb_field_is_empty($item, $field) {
  if (empty($item['rgb']) || empty($item['label'])) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Implements hook_field_validate().
 */
function rgb_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach($items as $delta => $item) {
    if (!empty($item['rgb'])) {
      // Make sure it's 6 characters.
      if (drupal_strlen($item['rgb']) !== 6) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'rgb_length',
          'message' => t('%name: the hex color must be 6 characters.', array('%name' => $instance['label'])),
        );
      }
    }
  }
}

hook_field_validate()

hook_field_is_empty()