You are here

function fraction_field_widget_form in Fraction 7

Implements hook_field_widget_form().

File

./fraction.field.inc, line 218
Fraction Field API functions

Code

function fraction_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $numerator = isset($items[$delta]['numerator']) ? $items[$delta]['numerator'] : '';
  $denominator = isset($items[$delta]['denominator']) ? $items[$delta]['denominator'] : '';
  $settings = $instance['widget']['settings'];
  switch ($instance['widget']['type']) {

    // Default fraction widget: two textfields (numerator and denominator).
    case 'fraction_default':
      $element['#type'] = 'fieldset';
      $element['numerator'] = array(
        '#type' => 'textfield',
        '#title' => t('Numerator'),
        '#default_value' => $numerator,
        '#element_validate' => array(
          'element_validate_integer',
        ),
        '#size' => 15,
      );
      $element['denominator'] = array(
        '#type' => 'textfield',
        '#title' => t('Denominator'),
        '#default_value' => $denominator,
        '#element_validate' => array(
          'element_validate_integer',
        ),
        '#size' => 15,
      );
      break;

    // Decimal widget: a single textfield that accepts a decimal number.
    // The default value is converted to a decimal with the specified precision.
    case 'fraction_decimal':
      $default_value = '';
      if (!empty($items[$delta]) && !fraction_field_is_empty($items[$delta], $field)) {
        $auto_precision = !empty($settings['auto_precision']) ? TRUE : FALSE;
        $default_value = fraction($numerator, $denominator)
          ->toDecimal($settings['precision'], $auto_precision);
      }
      $element['#element_validate'] = array(
        '_fraction_decimal_widget_validate',
      );
      $element['decimal'] = array(
        '#type' => 'textfield',
        '#title' => $element['#title'],
        '#description' => $element['#description'],
        '#default_value' => $default_value,
        '#element_validate' => array(
          'element_validate_number',
        ),
        '#size' => 15,
      );

      // Add prefix and suffix.
      if (!empty($instance['settings']['prefix'])) {
        $prefixes = explode('|', $instance['settings']['prefix']);
        $element['#field_prefix'] = field_filter_xss(array_pop($prefixes));
      }
      if (!empty($instance['settings']['suffix'])) {
        $suffixes = explode('|', $instance['settings']['suffix']);
        $element['#field_suffix'] = field_filter_xss(array_pop($suffixes));
      }
      break;
  }
  return $element;
}