You are here

protected function OptionsLimitWebformHandler::setOptionsElementDefaultValue in Webform 8.5

Same name and namespace in other branches
  1. 6.x modules/webform_options_limit/src/Plugin/WebformHandler/OptionsLimitWebformHandler.php \Drupal\webform_options_limit\Plugin\WebformHandler\OptionsLimitWebformHandler::setOptionsElementDefaultValue()

Set an options element's default value.

Parameters

array $element: An options element with limits.

array $limits: An options element's option limits.

array $reached: An options element's reached options.

string $operation: The form's current operation.

1 call to OptionsLimitWebformHandler::setOptionsElementDefaultValue()
OptionsLimitWebformHandler::alterElement in modules/webform_options_limit/src/Plugin/WebformHandler/OptionsLimitWebformHandler.php
Alter webform element.

File

modules/webform_options_limit/src/Plugin/WebformHandler/OptionsLimitWebformHandler.php, line 594

Class

OptionsLimitWebformHandler
Webform options and boolean (boolean) limit handler.

Namespace

Drupal\webform_options_limit\Plugin\WebformHandler

Code

protected function setOptionsElementDefaultValue(array &$element, array $limits, array $reached, $operation) {
  $webform_element = $this
    ->getWebformElement();
  $has_multiple_values = $webform_element
    ->hasMultipleValues($element);

  // Make sure the test default value is an enabled option.
  if ($operation === 'test') {
    $test_values = array_keys($reached ? array_diff_key($limits, $reached) : $limits);
    if ($test_values) {
      $test_value = $test_values[array_rand($test_values)];
      $element['#default_value'] = $has_multiple_values ? [
        $test_value,
      ] : $test_value;
    }
    else {
      $element['#default_value'] = $has_multiple_values ? [] : NULL;
    }
  }
  elseif (!empty($element['#default_value'])) {
    $default_value = $element['#default_value'];
    if ($has_multiple_values) {
      if ($this
        ->isTableSelectElement()) {
        $element['#default_value'] = array_diff($default_value, $reached);
      }
      else {
        $element['#default_value'] = array_values(array_diff($default_value, $reached));
      }
    }
    else {
      if (isset($reached[$default_value])) {
        $element['#default_value'] = $has_multiple_values ? [] : NULL;
      }
    }
  }
}