silverstripe / silverstripe-framework

Silverstripe Framework, the MVC framework that powers Silverstripe CMS
https://www.silverstripe.org
BSD 3-Clause "New" or "Revised" License
722 stars 821 forks source link

TimeField should deal better with partial times #11172

Open lekoala opened 6 months ago

lekoala commented 6 months ago

Description

Not technically a bug, but still annoying...

When using a timefield not in html5, when you enter a partial value (10:00) it will fail because it doesn't match the format (hh:mm:ss)... but that's also kind of too strict

I would suggest to expand value as needed (expand 10:00 to 10:00:00) if the input is smaller than the pattern

Additional context or points of discussion

Here is an example of what I did in my own class. Side benefit : no need to have a distinct handling of html5 vs non html5 inputs, they are all treated equal.

    /**
     * Convert frontend time to the internal representation (ISO 8601).
     * The frontend time is also in ISO 8601 when $html5=true.
     *
     * @param string $time
     * @return ?string The formatted time, or null if not a valid time
     */
    protected function frontendToInternal($time)
    {
        if (!$time) {
            return null;
        }
        $fromFormatter = $this->getFrontendFormatter();
        $toFormatter = $this->getInternalFormatter();

        // Expand time as needed by increment of 3 using :00
        $patternLength = strlen($fromFormatter->getPattern());
        while (strlen($time) < $patternLength) {
            $time .= ":00";
        }

        $timestamp = $fromFormatter->parse($time);

        // If timestamp still can't be detected, we've got an invalid time
        if ($timestamp === false) {
            return null;
        }

        return $toFormatter->format($timestamp);
    }

Validations

PRs

GuySartorelli commented 6 months ago

Sounds like a great idea! I'd definitely welcome a PR that implements this, provided it's BC safe of course.