You are here

public function WebformUiElementFormBase::getDefaultKey in Webform 6.x

Same name and namespace in other branches
  1. 8.5 modules/webform_ui/src/Form/WebformUiElementFormBase.php \Drupal\webform_ui\Form\WebformUiElementFormBase::getDefaultKey()

Get the default key for the current element.

Default key will be auto incremented when there are duplicate keys.

Return value

null|string An element's default key which will be incremented to prevent duplicate keys.

1 call to WebformUiElementFormBase::getDefaultKey()
WebformUiElementFormBase::buildForm in modules/webform_ui/src/Form/WebformUiElementFormBase.php
Form constructor.

File

modules/webform_ui/src/Form/WebformUiElementFormBase.php, line 601

Class

WebformUiElementFormBase
Provides a base class for webform element webforms.

Namespace

Drupal\webform_ui\Form

Code

public function getDefaultKey() {
  $element_plugin = $this
    ->getWebformElementPlugin();
  if (empty($element_plugin
    ->getDefaultKey())) {
    return NULL;
  }
  $base_key = $element_plugin
    ->getDefaultKey();
  $elements = $this
    ->getWebform()
    ->getElementsDecodedAndFlattened();
  if (preg_match('/(^|_)(\\d+$)($|_)/', $base_key) && !isset($elements[$base_key])) {
    return $base_key;
  }
  $increment = NULL;
  foreach ($elements as $element_key => $element) {
    if (strpos($element_key, $base_key) === 0) {
      if (preg_match('/^' . $base_key . '_(\\d+)$/', $element_key, $match)) {
        $element_increment = intval($match[1]);
        if ($element_increment > $increment) {
          $increment = $element_increment;
        }
      }
      elseif ($increment === NULL) {
        $increment = 0;
      }
    }
  }
  if ($increment === NULL) {
    return $base_key;
  }
  else {
    return $base_key . '_' . str_pad($increment + 1, 2, '0', STR_PAD_LEFT);
  }
}