-1

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

Here is my code:

// INSIDE FORM_ALTER

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

//THE METHOD

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

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');
1

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]
  ->prepareFormat('Y-m-d');
  • 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 – Bernard Brillo Jan 29 '18 at 3:50

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.