1

Some browsers (e.g. Safari) allow rubbish dates to slip through a form Date field so that we get a fatal PHP error (Call to a member function format() on null) when we invoke the DrupalDateTime::format() per the code below which doesn't catch any exception.

The user can type 19-00 into the time part of the date field instead of 19:00:00 and this will cause Drupal 8.0.5 to crash.

What is the correct way to test that a date in a DrupalDateTime object in the form array can be formatted properly? This doesn't work (snippet from an entity_builder for new and changed Meeting Nodes in our Meeting module):

try {
    $formatted_date_of_meeting = $date_of_meeting->format('l, j F Y');
} catch (\Exception $e) {
    $form_state->setError($form, $e->getMessage());
}
$node->setTitle($name_of_meeting.' on '.$formatted_date_of_meeting);

1 Answer 1

2

If the date is valid, then the form state will return an object of type Drupal\Core\Datetime\DrupalDateTime, and otherwise it will return an array with the invalid values. Since the invalid date format will be caught elsewhere, the custom code need only check if the value is an instance of DrupalDateTime:

if ($date_of_meeting instanceof DrupalDateTime) {
  $formatted_date_of_meeting = $date_of_meeting->format('l, j F Y');
  $node->setTitle($name_of_meeting.' on '.$formatted_date_of_meeting);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.