Fix ajax resets the value to current date if user only entered year

Created on 21 June 2024, 7 days ago

Problem/Motivation

When you have a date picker inside the referenced entity that has only years to choose from; all date field values reset to the current date whenever you have any Ajax request.

Steps to reproduce

- set format to yyyy
- set max view to years
- have the field inside any referenced entity.
- try to collapse or add a new reference item.
- observe the issue

Proposed resolution

Handling year-only values by creating datetime object from that year making it have yyyy-01-01 00:00:00 timestamp

      // Regular expression to check for a year-only input
      $year_regex = '/^\d{4}$/';

      // Check if the input matches the year-only format
      if (preg_match($year_regex, $element['#value'])) {
        // Create a DateTime object with the year only
        $date = DateTime::createFromFormat('Y', $element['#value']);

      } else {
        // Otherwise, try to create the DateTime object with the input directly
        $date = new DateTime($element['#value']);
      }
    
      // Convert it to DrupalDateTime
      $drupal_date = DrupalDateTime::createFromDateTime($date);

instead of
$new_date = new DrupalDateTime($element['#value']); Which gives the current date if time are not valid or not enough to make Drupal time stamp

Remaining tasks

User interface changes

API changes

Data model changes

πŸ› Bug report
Status

Active

Version

2.0

Component

Code

Created by

πŸ‡―πŸ‡΄Jordan Ahmad Khader

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.69.0 2024