3

I have a simple form element using datelist as the type. I need to validate this to make sure the date is in the future. But I cannot work out how to access the date itself in the validation method.

Form:

public function buildForm(array $form, FormStateInterface $form_state) {

  $form['date_field'] = array(
    '#title' => $this->t('Expiry'),
    '#type' => 'datelist',
    '#date_part_order' => array('month', 'year'),
    '#date_year_range' => '2017:2027',
    '#date_increment' => 1
  );

  return $form;
}

Validation:

public function validateForm(array &$form, FormStateInterface $form_state) {

  $date_input = $form_state->getValue('date_field');

  if(strtotime(date($date_input)) < strtotime(date('now'))) {  
    $form_state->setErrorByName('date_field', $this->t('The date must be in the future.'));
  }
} 

From the above, $date_input currently returns an object (see below). Essentially, I want to access $date_input->dateTimeObject->date; but doing exactly that will return a fatal error.

Fatal error: Cannot access protected property Drupal\Core\Datetime\DrupalDateTime::$dateTimeObject

$date_input object:

stdClass Object
(
    [__CLASS__] => Drupal\Core\Datetime\DrupalDateTime
    [formatTranslationCache] => 
    [dateParts] => Array
        (
            [0] => year
            [1] => month
            [2] => day
            [3] => hour
            [4] => minute
            [5] => second
        )

    [inputTimeRaw] => 
    [inputTimeAdjusted] => 
    [inputTimeZoneRaw] => 
    [inputTimeZoneAdjusted] => 
    [inputFormatRaw] => 
    [inputFormatAdjusted] => 
    [langcode] => en
    [errors] => Array
        (
        )

    [dateTimeObject] => stdClass Object
        (
            [__CLASS__] => DateTime
            [date] => 2027-12-01T00:00:00+11:00
            [timezone] => Australia/Sydney
        )

    [stringTranslation] => 
)

I could do something like:

$form_state->getValue('date_field')->format('d m Y');

But I suspect there is a better way?

1

Yes, to compare the date it's better to use the unix timestamp. You can get it by using the method getTimeStamp() and compare it to the current date:

      $value = $form_state->getValue('date_field');
      if ($value->getTimeStamp() > REQUEST_TIME) {
        drupal_set_message('Time is in the future');
      }

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.