Problem/Motivation

#3025642: Remove the try/catch block from DateTimeComputed::getValue() revealed this bug.

If a date field is empty, trying to get the date computed property on it causes DateTimeComputed to try to create a date object, which causes DrupalDateTime to throw an exception. Currently that exception is caught, but the patch at #3025642: Remove the try/catch block from DateTimeComputed::getValue() re-throws it.

Steps to reproduce

  1. Install the latest version of Drupal 11.x using the standard profile
  2. Navigate to admin/structure/types/manage/article/fields and add a date field to the Article content type
  3. Create a node of the article content type
  4. Save the node with the date field empty and try to get the date computed property

Proposed resolution

It doesn't make sense to attempt to create a date if we know there's no source value anyway, so DateTimeComputed should return early in that case.

Remaining tasks

  • Fix any pipeline errors
  • Make sure test coverage is adequate
  • Review the code

User interface changes

N/A

Introduced terminology

N/A

API changes

TBD

Data model changes

N/A

Release notes snippet

TBD

Issue fork drupal-3052608

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

joachim created an issue. See original summary.

joachim’s picture

Status: Active » Needs review
StatusFileSize
new721 bytes
jian he’s picture

Status: Needs review » Reviewed & tested by the community

The patch solved the issue.

Status: Reviewed & tested by the community » Needs work
yogeshmpawar’s picture

Status: Needs work » Reviewed & tested by the community

All looks good so setting back to RTBC! Tests failure is not related (see #3055648: Frequent random fail in \Drupal\Tests\media_library\FunctionalJavascript\MediaLibraryTest).

wim leers’s picture

Status: Reviewed & tested by the community » Needs work
Issue tags: +Needs tests

Sorry, but this still needs an explicit test.

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.0-alpha1 will be released the week of October 14th, 2019, which means new developments and disruptive changes should now be targeted against the 8.9.x-dev branch. (Any changes to 8.9.x will also be committed to 9.0.x in preparation for Drupal 9’s release, but some changes like significant feature additions will be deferred to 9.1.x.). For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

matthiasm11’s picture

When using date range items, $value can be an array containing empty values:

Array
(
    [year] => '',
    [month] => '',
    [day] => '',
    [hour] => '',
    [minute] => '',
    [object] => null
)

Since createFromFormat() expects a string value, we should not only check if $value is empty (NULL or an empty string), but also if it's a string before calling createFromFormat().

Steps to reproduce:

  • Create a paragraph with a required daterange field.
  • Create a node type with a reference to the paragraph.
  • Create a node, click the "add paragraph"-button.
  • Leave the daterange field empty and click the "add paragraph"-button again.
  • This results in an ajax error: Warning: DateTime::createFromFormat() expects parameter 2 to be string, array given in /var/www/web/core/lib/Drupal/Component/Datetime/DateTimePlus.php.
  • This can be fixed by the attached patch.
hardik_patel_12’s picture

Status: Needs work » Needs review

Version: 8.9.x-dev » 9.1.x-dev

Drupal 8.9.0-beta1 was released on March 20, 2020. 8.9.x is the final, long-term support (LTS) minor release of Drupal 8, which means new developments and disruptive changes should now be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

kishor_kolekar’s picture

I've re-rolled patch for 9.1

Version: 9.1.x-dev » 9.2.x-dev

Drupal 9.1.0-alpha1 will be released the week of October 19, 2020, which means new developments and disruptive changes should now be targeted for the 9.2.x-dev branch. For more information see the Drupal 9 minor version schedule and the Allowed changes during the Drupal 9 release cycle.

Version: 9.2.x-dev » 9.3.x-dev

Drupal 9.2.0-alpha1 will be released the week of May 3, 2021, which means new developments and disruptive changes should now be targeted for the 9.3.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.0-rc1 was released on November 26, 2021, which means new developments and disruptive changes should now be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.0-alpha1 was released on May 6, 2022, which means new developments and disruptive changes should now be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

tunprog’s picture

I've re-rolled patch for 9.3

bvoynick’s picture

Status: Needs review » Needs work

Still needs tests

Version: 9.5.x-dev » 10.1.x-dev

Drupal 9.5.0-beta2 and Drupal 10.0.0-beta2 were released on September 29, 2022, which means new developments and disruptive changes should now be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

benjifisher’s picture

We need to clarify the scope of this issue.

The issue description has not changed since this issue was created. The bug described there does not show up unless you apply one of the patches for #3025642: Remove the try/catch block from DateTimeComputed::getValue().

The first patch on this issue, in #2, tests empty($value). In the current 10.1.x, there is a very similar test of $value === NULL. So it may be that the original bug described here was already fixed in #3240181: \Drupal\datetime\DateTimeComputed::getValue() causes deprecations on PHP 8.1. I am adding that as a related issue.

Comment #8 describes steps to reproduce that involve the Paragraphs module. The patch in that comment, and the later patches, all test empty($value) || !is_string($value). That looks like it is fixing a different problem, and that problem may be in the Paragraphs module, not in Drupal core.

Is there a bug here that can be reproduced with just Drupal core? I tried to do something like the steps to reproduce in #8. I added a Datetime field to a content type, allowing unlimited values. If I make the field required and try to add a second instance while the first is empty, then I get a form validation error. If the field is not required, then I can add as many empty ones as I like, and they are clearly being added with AJAX calls. It looks as though $value is NULL in these cases.

If the original problem has been fixed, then let's close this issue as outdated. If we can reproduce a bug with just Drupal core, then let's add steps to reproduce in the issue summary. If the problem is actually with Paragraphs, then let's open an issue for that module.

bvoynick’s picture

I am seeing something similar come up in some instances involving AJAX and form rebuilding, which I think is probably the motivation for #16. The scope does indeed lie beyond instances of a NULL value - rather, the problem is an array value. So far I am not able to reproduce in Core alone without contrib. However, I think limit_validation_errors may be hiding this problem in Core-only AJAX cases I have tried testing.

The value getting set to an array does lie in Core. More details are in this issue: https://www.drupal.org/project/drupal/issues/3313231 There is a fatal on array values even without #3025642 - and while I think Paragraphs is related, I don't think it's to blame. As noted in that ticket, there seems to be an issue with inconsistent override of $form_state in Datetime and DateList elements. I think it's likely that element classes issue together with a perfect storm of AJAX, a heavy hand in rebuilding such as in Paragraph widgets, and contexts where limit_validation_errors does not happen to prevent this from coming up.

I am not certain whether this is best addressed...

  • In the two elements extending DateElementBase, described more in #3313231 - possibly cleanest since these are where the "invalid" array value for the date is introduced, but it also means wiping out non-empty but invalid values for DateList.
  • In DateTimeComputed. (Either the type of the value needs to be validated, as with the is_string() check in #13; or else would need to not only continue using try/catch, but expand the catch to either \Exception|\TypeError or \Throwable because passing the wrong argument type from date elements is an Error rather than Exception.)
  • Somewhere else? In an ideal world maybe we could prevent array values from being passed on to DateTimeComputed while allowing them to stay in $form_state, but I'm not sure how that would work. But I may not know enough about the Typed Data API & the form building process to see the path forward in this direction.
alexpott’s picture

+++ b/core/modules/datetime/src/DateTimeComputed.php
@@ -46,8 +46,7 @@ public function getValue() {
+    if (empty($value) || !is_string($value)) {
       return NULL;

I think this should be
if (!is_string($value) && $value !== '') {

if $value = '0'; then empty($value) will return TRUE.

We really need some tests here. And a reason why the value is not a NULL or string at this point.

tanuj.’s picture

StatusFileSize
new561 bytes
new461 bytes

updated patch after addressing points from #21, still needs tests tho.

tanuj.’s picture

Status: Needs work » Needs review

unrelated failure, retest is green. please review.

smustgrave’s picture

Status: Needs review » Needs work
Issue tags: +Needs Review Queue Initiative, +Needs issue summary update

@Tanuj thank you for the interest.

This was previously tagged for tests which weren't added.

Issue summary should be updated to highlight proposed solution.

Please do some basic checks before putting in review.

Thanks.

carlitus’s picture

The #22 patch resolves for me the problem.

I have a paragraph with some required fields.

Without de patch when I upload a image I get an ajax error and the image is not uploaded.
Without the patch

And with the patch it works well:
With the patch

Version: 10.1.x-dev » 11.x-dev

Drupal core is moving towards using a “main” branch. As an interim step, a new 11.x branch has been opened, as Drupal.org infrastructure cannot currently fully support a branch named main. New developments and disruptive changes should now be targeted for the 11.x branch, which currently accepts only minor-version allowed changes. For more information, see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

millnut’s picture

Confirming this patch 16 fixes my issue in Drupal 9.5.x, with the minimal test case below.

- Creating new content
- Required Date field in a paragraph with no default value set
- Using media library for an image field

Results in an AJAX error and the media library popup not opening

2pha’s picture

I hit this too...
I have...
A profile with a required date field with no default value.
This profile is required to be filled on user creation (so shows on the "add user" page).
All is ok until I add a password policy (which maybe forces a form rebuild?)
When adding a user and I tab away from the password field, ajax is fired and I get the "DateTime::createFromFormat(): Argument #2 ($datetime) must be of type string" error.
The $time variable used as the second parameter sent to createFromFormat is an array in this case.
If I set a value on the required date field before trying to set the password, I don't get the error and the $time variable is a string.

Patch #22 worked for me

grimreaper’s picture

Hi,

I am not sure if this is related, but I had the same problem when I had a value set in my daterange field. And when trying to isolate the problem, in my case I ended up with a simple date field for a very specific datetime #3410541: On Paris timezone, impossible to set a date to 2023/03/31 02:00:00.

If this may help to have reproducible steps.

fjgarlin’s picture

We had exactly the same situation described in #25 and the patch in #22 fixed the issue.

fjgarlin’s picture

Issue tags: +affects drupal.org
fjgarlin’s picture

Full backtrace in case it helps for writing tests

TypeError: DateTime::createFromFormat(): Argument #2 ($datetime) must be of type string, array given in DateTime::createFromFormat() (line 251 of /app/web/core/lib/Drupal/Component/Datetime/DateTimePlus.php).

#0 /app/web/core/lib/Drupal/Component/Datetime/DateTimePlus.php(251): DateTime::createFromFormat()
#1 /app/web/core/modules/datetime/src/DateTimeComputed.php(57): Drupal\Component\Datetime\DateTimePlus::createFromFormat()
#2 /app/web/core/lib/Drupal/Core/Field/FieldItemBase.php(154): Drupal\datetime\DateTimeComputed->getValue()
#3 /app/web/core/modules/datetime_range/src/Plugin/Field/FieldWidget/DateRangeWidgetBase.php(33): Drupal\Core\Field\FieldItemBase->__get()
#4 /app/web/core/modules/datetime_range/src/Plugin/Field/FieldWidget/DateRangeDefaultWidget.php(59): Drupal\datetime_range\Plugin\Field\FieldWidget\DateRangeWidgetBase->formElement()
#5 /app/web/core/lib/Drupal/Core/Field/WidgetBase.php(459): Drupal\datetime_range\Plugin\Field\FieldWidget\DateRangeDefaultWidget->formElement()
#6 /app/web/core/lib/Drupal/Core/Field/WidgetBase.php(219): Drupal\Core\Field\WidgetBase->formSingleElement()
#7 /app/web/core/lib/Drupal/Core/Field/WidgetBase.php(120): Drupal\Core\Field\WidgetBase->formMultipleElements()
#8 /app/web/core/lib/Drupal/Core/Entity/Entity/EntityFormDisplay.php(186): Drupal\Core\Field\WidgetBase->form()
#9 /app/web/modules/contrib/paragraphs/src/Plugin/Field/FieldWidget/ParagraphsWidget.php(807): Drupal\Core\Entity\Entity\EntityFormDisplay->buildForm()
#10 /app/web/core/lib/Drupal/Core/Field/WidgetBase.php(459): Drupal\paragraphs\Plugin\Field\FieldWidget\ParagraphsWidget->formElement()
#11 /app/web/modules/contrib/paragraphs/src/Plugin/Field/FieldWidget/ParagraphsWidget.php(1353): Drupal\Core\Field\WidgetBase->formSingleElement()
#12 /app/web/core/lib/Drupal/Core/Field/WidgetBase.php(120): Drupal\paragraphs\Plugin\Field\FieldWidget\ParagraphsWidget->formMultipleElements()
#13 /app/web/modules/contrib/paragraphs/src/Plugin/Field/FieldWidget/ParagraphsWidget.php(1475): Drupal\Core\Field\WidgetBase->form()
#14 /app/web/core/lib/Drupal/Core/Entity/Entity/EntityFormDisplay.php(186): Drupal\paragraphs\Plugin\Field\FieldWidget\ParagraphsWidget->form()
#15 /app/web/core/lib/Drupal/Core/Entity/ContentEntityForm.php(121): Drupal\Core\Entity\Entity\EntityFormDisplay->buildForm()
#16 /app/web/core/modules/node/src/NodeForm.php(127): Drupal\Core\Entity\ContentEntityForm->form()
#17 /app/web/core/lib/Drupal/Core/Entity/EntityForm.php(107): Drupal\node\NodeForm->form()
#18 [internal function]: Drupal\Core\Entity\EntityForm->buildForm()
#19 /app/web/core/lib/Drupal/Core/Form/FormBuilder.php(536): call_user_func_array()
#20 /app/web/core/lib/Drupal/Core/Form/FormBuilder.php(375): Drupal\Core\Form\FormBuilder->retrieveForm()
#21 /app/web/core/lib/Drupal/Core/Form/FormBuilder.php(633): Drupal\Core\Form\FormBuilder->rebuildForm()
#22 /app/web/core/lib/Drupal/Core/Form/FormBuilder.php(325): Drupal\Core\Form\FormBuilder->processForm()
#23 /app/web/core/lib/Drupal/Core/Controller/FormController.php(73): Drupal\Core\Form\FormBuilder->buildForm()
#24 [internal function]: Drupal\Core\Controller\FormController->getContentResult()
#25 /app/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call_user_func_array()
#26 /app/web/core/lib/Drupal/Core/Render/Renderer.php(627): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
#27 /app/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer->executeInRenderContext()
#28 /app/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext()
#29 /app/vendor/symfony/http-kernel/HttpKernel.php(181): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
#30 /app/vendor/symfony/http-kernel/HttpKernel.php(76): Symfony\Component\HttpKernel\HttpKernel->handleRaw()
#31 /app/web/core/lib/Drupal/Core/StackMiddleware/Session.php(58): Symfony\Component\HttpKernel\HttpKernel->handle()
#32 /app/web/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(48): Drupal\Core\StackMiddleware\Session->handle()
#33 /app/web/core/lib/Drupal/Core/StackMiddleware/ContentLength.php(28): Drupal\Core\StackMiddleware\KernelPreHandle->handle()
#34 /app/web/core/modules/big_pipe/src/StackMiddleware/ContentLength.php(32): Drupal\Core\StackMiddleware\ContentLength->handle()
#35 /app/web/core/modules/page_cache/src/StackMiddleware/PageCache.php(106): Drupal\big_pipe\StackMiddleware\ContentLength->handle()
#36 /app/web/core/modules/page_cache/src/StackMiddleware/PageCache.php(85): Drupal\page_cache\StackMiddleware\PageCache->pass()
#37 /app/web/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(48): Drupal\page_cache\StackMiddleware\PageCache->handle()
#38 /app/web/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(51): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle()
#39 /app/web/core/lib/Drupal/Core/StackMiddleware/AjaxPageState.php(36): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle()
#40 /app/web/core/lib/Drupal/Core/StackMiddleware/StackedHttpKernel.php(51): Drupal\Core\StackMiddleware\AjaxPageState->handle()
#41 /app/web/core/lib/Drupal/Core/DrupalKernel.php(704): Drupal\Core\StackMiddleware\StackedHttpKernel->handle()
#42 /app/web/index.php(19): Drupal\Core\DrupalKernel->handle()
#43 {main}

fjgarlin’s picture

I've moved #22 to an MR here https://git.drupalcode.org/project/drupal/-/merge_requests/7585/diffs
So we can continue development and testing there.

I don't think that there are tests that were checking the NULL case before, so I'm not sure where to best place the tests. In fact, I don't see any tests for DateTimeComputed yet. Maybe some guidance here would help move the issue forward.

jawadharaba98’s picture

I am having the same issue on Drupal 10.3.2

nehajyoti’s picture

StatusFileSize
new453 bytes
new453 bytes

Latest Patch to fix this issue (occured while drupal core upgrade from 10.3.* to 10.4.3)

rob230’s picture

I get this in Drupal 10.4 - just have any AJAX request (such as an "add another value") in a multiple paragraphs field, and it will fail with this error if there is a date field that you haven't populated yet.

The patch #36 fixes it.

This appears to be the same issue as #3313231: DateTimeComputed: Fatal error when Ajax call in form. (strlen() on array) but the fix in this issue makes more sense to me.

riyas_nr made their first commit to this issue’s fork.

riyas_nr’s picture

Status: Needs work » Needs review

Added test coverage for passing non-string values to DateTimeComputed::getValue(). Moving to NR.

tame4tex made their first commit to this issue’s fork.

tame4tex’s picture

I was able to reproduce the bug in core in a FunctionalJavascript test using NestedEntityTestForm from the field_test module. This test has been committed to the MR of #3313231: DateTimeComputed: Fatal error when Ajax call in form. (strlen() on array). Also see comment #21 on that issue.

I have also updated that issue with an alternative solution that removes the need to modify DateTimeComputed::getValue.

This issue could possibly be closed as a duplicate of #3313231: DateTimeComputed: Fatal error when Ajax call in form. (strlen() on array). But I guess it begs the question, is it right for DateTimeComputed::getValue to expect the value to either be a string or NULL? I propose it is and stricter typing should be applied by throwing a helpful exception. If that is the case, then this issue, if not closed as a duplicate of #3313231: DateTimeComputed: Fatal error when Ajax call in form. (strlen() on array), should be closed as a duplicate of #3025642: Remove the try/catch block from DateTimeComputed::getValue() or #3213054: DateTimeComputed is suppressing date errors silently.

smustgrave’s picture

Status: Needs review » Needs work

Think this one needs an issue summary first.

ironnuts’s picture

Issue summary: View changes
Issue tags: -Needs tests, -Needs issue summary update

Added the IS template and created steps to reproduce (more steps and more detail would be useful).

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.

herved made their first commit to this issue’s fork.

herved’s picture

Rebased the MR

The project I work on needed this exactly for the scenario described in the other issue - nested paragraphs and empty required date field then click add more - #3313231: DateTimeComputed: Fatal error when Ajax call in form. (strlen() on array) I can confirm it also fixes the issue.

liam morland made their first commit to this issue’s fork.

liam morland’s picture

Status: Needs work » Needs review

I have corrected the conditional that it ensures $value is a non-empty string. This fix seems to be working.

There is a try/catch block, but that would catch an exception, not a type error.