Jump to content

Hook to prevent date fields from changing incorrectly-formatted input values? (erase instead)


Recommended Posts

Posted (edited)

PW date fields allow imperfectly-entered date strings, but they will change upon save, with no warning.

This hook for text fields allows for values such as 2020 or 2020-00-00 or 2020-05.
This is stupid because strtotime($saidstring) equate to something slightly or drastically different... 

I added a hook to allow for approximate dates in a text field in init.php, but this is bad because it can be easily mis-parsed, and 2020-00-01 is allowed so it's dumb, and year/month/day should be discrete inputs (for approximation):

$pages->addHookAfter('Pages::saveReady', 'hook_validate_field_strtotime');
function hook_validate_field_strtotime(HookEvent $event) {
    $page = $event->arguments(0);
    $fldn = 'dated';
    if (!$page->hasField($fldn) || empty($page->$fldn)) return;

    $ts = strtotime($page->$fldn);
    if ($ts) return;

    $page->setAndSave($fldn, '', ['noHooks' => true]);
    wire()->warning("Field $fldn value {$page->$fldn} does not validate as a date, and was removed.");
}

I'm trying to hook into this to remedy the changing date text inputs:

$this->addHookAfter('InputfieldDatetime::processInput', function(HookEvent $event) {
    // Get the object the event occurred on, if needed
    $InputfieldDatetime = $event->object;

    // An 'after' hook can retrieve and/or modify the return value
    $return = $event->return;

    // Get values of arguments sent to hook (if needed)
    $input = $event->arguments(0);

    /* Your code here, perhaps modifying the return value */
	$dfldn = 'dated';
    $value = ($input[$dfldn]);

    // Populate back return value, if you have modified it
    $event->return = $return;
});

How can I ensure that InputfieldDatetime fields' text inputs match the values saved? i.e., not save the value if the input value doesn't match the processed input value, and display a warning/error, rather than change it to some other date with no message

Edited by hellomoto
  • hellomoto changed the title to Hook to prevent date fields from changing incorrectly-formatted input values? (erase instead)

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...