You are here

function cck_select_other_field_widget_form in CCK Select Other 7.2

Same name and namespace in other branches
  1. 7 cck_select_other.module \cck_select_other_field_widget_form()

Implementation of hook_field_widget_form().

File

./cck_select_other.module, line 109
Implements a select list widget that lets a user provide an alternate option.

Code

function cck_select_other_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $options = cck_select_other_options($instance);

  // Setup select other wrapper.
  $element += array(
    '#bundle' => $instance['bundle'],
    '#field_name' => $field['field_name'],
    '#langcode' => $langcode,
    '#element_validate' => array(
      'cck_select_other_widget_validate',
    ),
    '#pre_render' => array(
      'cck_select_other_widget_pre_render',
    ),
    '#attributes' => array(
      'class' => array(
        'form-select-other-wrapper',
        'cck-select-other-wrapper',
      ),
    ),
  );

  // Setup select list.
  $element['select_other_list'] = array(
    '#title' => $element['#title'],
    '#description' => $element['#description'],
    '#type' => 'select',
    '#options' => $options,
    '#required' => $instance['required'],
    '#attributes' => array(
      'class' => array(
        'form-text form-select form-select-other-list',
      ),
    ),
  );

  // Setup text input.
  $element['select_other_text_input'] = array(
    '#type' => 'textfield',
    '#title' => t('Provide other option'),
    '#title_display' => 'invisible',
    '#size' => 60,
    '#attributes' => array(
      'class' => array(
        'form-text form-select-other-text-input',
      ),
    ),
  );

  // Default empty values.
  $list_default = $instance['required'] ? '' : '_none';
  $text_default = '';
  $value = '';
  if (isset($items[$delta]['value'])) {

    // Use the value provided in items.
    $value = $items[$delta]['value'];
  }
  elseif (isset($instance['default_value'])) {

    // Use the default value of the field if it is set.
    $value = $instance['default_value'][0]['value'];
  }
  if ($value && in_array($value, array_keys($options))) {

    // Value is not empty and value is in the list.
    $list_default = $value;
  }
  elseif ($value) {

    // Set the list default to other.
    $list_default = 'other';
    $text_default = $value;
  }

  // Set default values.
  $element['select_other_list']['#default_value'] = $list_default;
  $element['select_other_text_input']['#default_value'] = $text_default;
  return $element;
}