Check your version

This video 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: 

Validating and Saving Field Data

Video loading...

Join Drupalize.Me to watch this video

Join today and gain instant access to our entire video library.

Log in Sign up
  • 0:03
    Field Data with Joe Shindelar
  • 0:07
    [WATER DROP NOISE]
  • 0:07
    With a field widget in place,
  • 0:09
    we can now collect data from users for our field.
  • 0:12
    However, before we can save that in the database,
  • 0:14
    the field API requires us to validate the data
  • 0:17
    and prove its existence.
  • 0:18
    In this Lesson
  • 0:19
    JOE SHINDELAR: In this lesson, we're going
  • 0:21
    to implement hook_field_is_empty, which is called whenever data

Validating and Saving Field Data

Loading...

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'])),
        );
      }
    }
  }
}
Downloads: 
Log in or sign up to download companion files.