You are here

function cshs_element_validate in Client-side Hierarchical Select 7

Validation handler.

1 string reference to 'cshs_element_validate'
cshs_element_info in ./cshs.element.inc
Implements hook_element_info().

File

./cshs.element.inc, line 78

Code

function cshs_element_validate(&$element, &$form_state) {
  $value = $element['#value'];
  $title = $element['#label'];

  // Try to translate the title.
  if (module_exists('i18n_field') && isset($element['#field_name'])) {
    $instance = field_info_instance($element['#entity_type'], $element['#field_name'], $element['#entity']->type);
    $title = i18n_field_translate_property($instance, 'label');
  }

  // Collect settings.
  $force_deepest = $element['#force_deepest'];
  $none_value = $element['#none_value'];

  // If _none, then empty the value.
  if ($value == $none_value) {
    form_set_value($element, NULL, $form_state);
  }

  // See if we are on the field settings form.
  if ($form_state['complete form']['#form_id'] == 'field_ui_field_edit_form') {
    return;
  }

  // Check if not empty.
  if ($element['#required'] && $value == $none_value) {
    form_error($element, t('!name field is required.', array(
      '!name' => $title,
    )));
  }

  // Do we want to force the user to select terms from the deepest level?
  if ($force_deepest && $value != $none_value) {

    // Try to load a term.
    $term = taxonomy_term_load($value);

    // See if it has children.
    $children = array();
    if ($term) {
      $vid = $term->vid;

      // Does the selected term has any children?
      $children = taxonomy_get_children($value, $vid);
    }

    // Set an error if it has children.
    if ($value == $none_value || count($children)) {
      form_error($element, t('You need to select a term from the deepest level in field %field_name.', array(
        '%field_name' => $title,
      )));
    }
  }
}