From 8a35c7ee2d45688cb68fdc6cafa8b05fc67f5401 Mon Sep 17 00:00:00 2001
From: eileen <emcnaughton@wikimedia.org>
Date: Mon, 6 Jul 2020 13:52:08 +1200
Subject: [PATCH] dev/core#1847 Fix datepicker to respect the searchDate
 offsets

I have some misgivings about this since I suspect the rationale behind the search offsets was primarily about the clunky UI.

Having said that I think the datepicker UI is a bit clunky on this front too as it's not obvious you can choose earlier
dates. This does at least restore established behaviour.

https://lab.civicrm.org/dev/core/-/issues/1847
---
 CRM/Core/Form.php | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)

diff --git a/CRM/Core/Form.php b/CRM/Core/Form.php
index ce97e2c655..1f0e6691a5 100644
--- a/CRM/Core/Form.php
+++ b/CRM/Core/Form.php
@@ -359,6 +359,8 @@ class CRM_Core_Form extends HTML_QuickForm_Page {
    *
    * @return HTML_QuickForm_Element
    *   Could be an error object
+   *
+   * @throws \CRM_Core_Exception
    */
   public function &add(
     $type, $name, $label = '',
@@ -385,8 +387,19 @@ class CRM_Core_Form extends HTML_QuickForm_Page {
       unset($attributes['multiple']);
       $extra = NULL;
     }
+
     // @see https://docs.civicrm.org/dev/en/latest/framework/ui/#date-picker
-    if ($type == 'datepicker') {
+    if ($type === 'datepicker') {
+      $attributes = $attributes ?: [];
+      if (!empty($attributes['format'])) {
+        $dateAttributes = CRM_Core_SelectValues::date($attributes['format'], NULL, NULL, NULL, 'Input');
+        if (empty($extra['minDate']) && !empty($dateAttributes['minYear'])) {
+          $extra['minDate'] = $dateAttributes['minYear'] . '-01-01';
+        }
+        if (empty($extra['maxDate']) && !empty($dateAttributes['minYear'])) {
+          $extra['maxDate'] = $dateAttributes['maxYear'] . '-12-31';
+        }
+      }
       // Support minDate/maxDate properties
       if (isset($extra['minDate'])) {
         $extra['minDate'] = date('Y-m-d', strtotime($extra['minDate']));
@@ -395,14 +408,13 @@ class CRM_Core_Form extends HTML_QuickForm_Page {
         $extra['maxDate'] = date('Y-m-d', strtotime($extra['maxDate']));
       }
 
-      $attributes = ($attributes ? $attributes : []);
       $attributes['data-crm-datepicker'] = json_encode((array) $extra);
       if (!empty($attributes['aria-label']) || $label) {
         $attributes['aria-label'] = CRM_Utils_Array::value('aria-label', $attributes, $label);
       }
       $type = "text";
     }
-    if ($type == 'select' && is_array($extra)) {
+    if ($type === 'select' && is_array($extra)) {
       // Normalize this property
       if (!empty($extra['multiple'])) {
         $extra['multiple'] = 'multiple';
-- 
2.25.1