You are here

public static function GranularityElement::processElement in Duration Field 3.0.x

Same name and namespace in other branches
  1. 8.2 src/Element/GranularityElement.php \Drupal\duration_field\Element\GranularityElement::processElement()

File

src/Element/GranularityElement.php, line 59

Class

GranularityElement
Provides the Granularity form element.

Namespace

Drupal\duration_field\Element

Code

public static function processElement(&$element, FormStateInterface $form_state, &$complete_form) {
  $value = FALSE;
  if (isset($element['#value']) && $element['#value']) {
    $value = $element['#value'];
  }
  elseif (isset($element['#default_value']) && $element['#default_value']) {
    $value = $element['#default_value'];
  }
  $granularities = explode(':', $value);
  $time_mappings = [
    'y' => t('Years'),
    'm' => t('Months'),
    'd' => t('Days'),
    'h' => t('Hours'),
    'i' => t('Minutes'),
    's' => t('Seconds'),
  ];

  // Create a wrapper for the elements. This is done in this manner
  // rather than nesting the elements in a wrapper with #prefix and #suffix
  // so as to not end up with [wrapper] as part of the name attribute
  // of the elements.
  $div = '<div';
  $classes = [
    'granularity-inner-wrapper',
  ];
  if (!empty($element['#states'])) {
    self::processStates($element);
  }
  foreach ($element['#attributes'] as $attribute => $attribute_value) {
    if (is_string($attribute_value)) {
      $div .= ' ' . $attribute . "='" . $attribute_value . "'";
    }
    elseif ($attribute == 'class') {
      $classes = array_merge($classes, $attribute_value);
    }
  }
  $div .= ' class="' . implode(' ', $classes) . '"';
  $div .= '>';
  $element['wrapper_open'] = [
    '#markup' => $div,
    '#weight' => -1,
  ];
  foreach ($time_mappings as $key => $label) {
    $element[$key] = [
      '#id' => $element['#id'] . '-' . $key,
      '#type' => 'checkbox',
      '#title' => $label,
      // Elements included in the #value or #default_value will be checked.
      '#default_value' => in_array($key, $granularities),
      '#weight' => 0,
      '#min' => 0,
    ];
    if (!empty($element['#ajax'])) {
      $element[$key]['#ajax'] = $element['#ajax'];
    }
  }
  $element['wrapper_close'] = [
    '#markup' => '</div>',
    '#weight' => 1,
  ];
  return $element;
}