You are here

public static function BootstrapDate::processBootstrapDate in Bootstrap Datepicker 8

File

src/Element/BootstrapDate.php, line 66

Class

BootstrapDate
Provides a BootstrapDate form element.

Namespace

Drupal\bootstrap_datepicker\Element

Code

public static function processBootstrapDate(&$element, FormStateInterface $form_state, &$complete_form) {

  // Default settings.
  $default_settings = BootstrapDatepickerBase::defaultSettings();

  // Load the Bootstrap datepicker via data-provide attribute.
  $settings = [
    'data-provide' => 'datepicker',
  ];

  // Load all bootstrap-datepicker settings in data-date attributes
  // only if they differ from default settings.
  foreach ($element as $key => $value) {
    $newKey = 'data-date-' . str_replace('_', '-', str_replace('#', '', $key));
    $dsKey = str_replace('#', '', $key);
    if (array_key_exists($dsKey, $default_settings)) {
      if ($default_settings[$dsKey] != $value) {

        // Javascript library needs 'true' or 'false in data- attribute.
        if ($element[$key] === '1') {
          $element[$key] = 'true';
        }
        if ($element[$key] === '0') {
          $element[$key] = 'false';
        }
        $settings[$newKey] = Html::escape($element[$key]);
      }
    }
  }

  // Load the Bootstrap datepicker title via data-provide attribute.
  $settings['data-date-title'] = $element['#datepicker_title'] ?? NULL;

  // Append our attributes to element.
  $element['#attributes'] += $settings;

  // Disable autocomplete widget.
  $element['#attributes']['autocomplete'] = 'off';

  // Attach library.
  $element['#attached']['library'][] = 'bootstrap_datepicker/datepicker';

  // Attach language library.
  $element['#attached']['library'][] = 'bootstrap_datepicker/datepicker_' . $element['#language'];

  // If a field value is set, convert Drupal default date format
  // to format from field widget settings. This could be removed after
  // https://www.drupal.org/project/drupal/issues/2936268 is fixed.
  if (!empty($element['#value'])) {
    $new_date = new DrupalDateTime($element['#value']);

    // Convert javascript date format to PHP date format.
    $pattern = [
      '/(?<!m)m(?!m)/i',
      '/mm/i',
      '/(?<!d)d(?!d)/i',
      '/dd/i',
      '/yyyy/i',
      '/yy/i',
    ];
    $replacement = [
      'n',
      'm',
      'j',
      'd',
      'o',
      'y',
    ];
    $date_format = preg_replace($pattern, $replacement, $element['#format']);
    $element['#value'] = $new_date
      ->format($date_format);
  }
  return $element;
}