You are here

public static function WebformCheckboxValue::processWebformCheckboxValue in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/Element/WebformCheckboxValue.php \Drupal\webform\Element\WebformCheckboxValue::processWebformCheckboxValue()

Processes a 'webform_checkbox_value' element.

File

src/Element/WebformCheckboxValue.php, line 52

Class

WebformCheckboxValue
Provides a webform element for checking a box before entering a value.

Namespace

Drupal\webform\Element

Code

public static function processWebformCheckboxValue(&$element, FormStateInterface $form_state, &$complete_form) {
  $element['#tree'] = TRUE;
  $properties = [
    '#title' => '#title',
    '#description' => '#description',
    '#help' => '#help',
  ];

  // Build checkbox element.
  $element['checkbox'] = [
    '#type' => 'checkbox',
    '#default_value' => !empty($element['#default_value']) ? TRUE : FALSE,
  ];
  $element['checkbox'] += array_intersect_key($element, $properties);

  // Build value element.
  $selector = 'edit-' . str_replace('_', '-', implode('-', $element['#parents'])) . '-checkbox';
  $element['value'] = [
    '#default_value' => $element['#default_value'],
    '#states' => [
      'visible' => [
        ':input[data-drupal-selector="' . $selector . '"]' => [
          'checked' => TRUE,
        ],
      ],
      'required' => [
        ':input[data-drupal-selector="' . $selector . '"]' => [
          'checked' => TRUE,
        ],
      ],
    ],
  ];

  // Pass '#value__*' properties to the value element.
  foreach ($element as $key => $value) {
    if (strpos($key, '#value__') === 0) {
      $value_key = str_replace('#value__', '#', $key);
      $element['value'][$value_key] = $value;
    }
  }

  // Pass entire element to the value element.
  if (isset($element['#element'])) {
    $element['value'] += $element['#element'];
  }

  // Make sure the value element has a #type.
  $element['value'] += [
    '#type' => 'textfield',
  ];

  // Always add a title to the value element for validation.
  if (!isset($element['value']['#title']) && isset($element['#title'])) {
    $element['value']['#title'] = $element['#title'];
    $element['value']['#title_display'] = 'invisible';
  }

  // Attach libraries.
  $element['#attached']['library'][] = 'webform/webform.element.checkbox_value';

  // Add validate callback.
  $element += [
    '#element_validate' => [],
  ];
  array_unshift($element['#element_validate'], [
    get_called_class(),
    'validateWebformCheckboxValue',
  ]);

  // Remove properties from the element.
  $element = array_diff_key($element, $properties);
  return $element;
}