You are here

function _form_options_validate in Options Element 7

Same name and namespace in other branches
  1. 6 options_element.inc \_form_options_validate()

Logic function for form_options_validate(). Do not call directly.

See also

form_options_validate()

1 call to _form_options_validate()
form_options_validate in ./options_element.module
Validate the "options" form element type.

File

./options_element.inc, line 200
All logic for options_element form elements.

Code

function _form_options_validate($element, &$form_state) {

  // Even though we already have the converted options in #value['options'], run
  // the conversion again to check for duplicates in the user-defined list.
  $duplicates = array();
  $options = form_options_from_text($element['#value']['options_text'], $element['#key_type'], empty($element['#optgroups']), $duplicates);

  // Check if a key is used multiple times.
  if (count($duplicates) == 1) {
    form_error($element, t('The key %key has been used multiple times. Each key must be unique to display properly.', array(
      '%key' => reset($duplicates),
    )));
  }
  elseif (!empty($duplicates)) {
    array_walk($duplicates, 'check_plain');
    $duplicate_list = theme('item_list', array(
      'items' => $duplicates,
    ));
    form_error($element, t('The following keys have been used multiple times. Each key must be unique to display properly.') . $duplicate_list);
  }

  // Add the list of duplicates to the page so that we can highlight the fields.
  if (!empty($duplicates)) {
    drupal_add_js(array(
      'optionsElement' => array(
        'errors' => drupal_map_assoc($duplicates),
      ),
    ), 'setting');
  }

  // Check if no options are specified.
  if (empty($options) && $element['#required']) {
    form_error($element, t('At least one option must be specified.'));
  }

  // Check for numeric keys if needed.
  if ($element['#key_type'] == 'numeric') {
    foreach ($options as $key => $value) {
      if (!is_int($key)) {
        form_error($element, t('The keys for the %title field must be integers.', array(
          '%title' => $element['#title'],
        )));
        break;
      }
    }
  }

  // Check that the limit of options has not been exceeded.
  if (!empty($element['#limit'])) {
    $count = 0;
    foreach ($options as $value) {
      if (is_array($value)) {
        $count += count($value);
      }
      else {
        $count++;
      }
    }
    if ($count > $element['#limit']) {
      form_error($element, t('The %title field supports a maximum of @count options. Please reduce the number of options.', array(
        '%title' => $element['#title'],
        '@count' => $element['#limit'],
      )));
    }
  }
}