I have an ajax callback on my date field that changes a particular field when user chooses a date.

Here is my code:


$form['field_camp_scheduled_time']['widget']['#options'] = populate_scheduled_time($form, $form_state);


function populate_scheduled_time($form, $form_state){
$date = $form_state->getValue('field_camp_scheduled_date')[0];

As you can see from the method above, I'm trying to get the value of the date field. But instead of getting the date '2018-26-01', I'm getting an array:

Drupal\Core\Datetime\DrupalDateTime Object ( [formatTranslationCache:protected] => [inputTimeRaw:protected] => [inputTimeAdjusted:protected] => [inputTimeZoneRaw:protected] => [inputTimeZoneAdjusted:protected] => [inputFormatRaw:protected] => [inputFormatAdjusted:protected] => [langcode:protected] => en [errors:protected] => Array ( ) [dateTimeObject:protected] => DateTime Object ( [date] => 2018-01-27 12:00:00.000000 [timezone_type] => 3 [timezone] => UTC ) [stringTranslation:protected] => )

3 Answers 3


I was able to get the value by using this code:

$date_value = $form_state->getValue('field_camp_scheduled_date')[0]['value'];

$date = new DrupalDateTime($date_value, DATETIME_STORAGE_TIMEZONE);

$value = $date->format('Y-m-d');

Drupal\Core\Datetime\DrupalDateTime is a class - what you have is an object, not an array.

Looking at the docs for the class, you'll find the prepareFormat method:

$formatted_date = $form_state->getValue('field_camp_scheduled_date')[0]
  • i received an ajax error @Clive♦ while trying your suggested code: An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /lbs/node/add/campaign?ajax_form=1 StatusText: OK ResponseText: ( ! ) Fatal error: Call to a member function prepareFormat() on array in C:\wamp64\www\lbs\modules\lbs_campaign\lbs_campaign.module on line 531 Call Stack #TimeMemoryFunctionLocation Jan 29, 2018 at 3:50

For some reason, creating a new date object from Bernard's answer above didn't work for me. If I cut out that step, it works fine for my webform alter.

$date_value = $form_state->getValue('field_camp_scheduled_date')[0]['value'];
$value = $date_value->format('Y-m-d');

I am running Drupal 8.9.6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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