0

I created a custom module for a form which accepts from date and to date as user input. I would like to restrict the user from selecting a date prior to current date.

Code snippet of my code

$form['oneway']['from_date'] = array (
  '#type' => 'date',
  '#title' => t('From Date'),
  '#date_year_range' => '-80:0',
  '#required' => TRUE,
);

Can someone please help me out?

  • what does your from date look like? d/m/Y 18/01/2016 ? OR ??? – No Sssweat Apr 21 '16 at 7:06
2

Approach to get today's date as Minimum date

Pass the JS options in '#datepicker_options'

$form['oneway']['from_date'] = array(
  '#title' => t('From Date'),
  '#type' => 'date_popup',
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '-80:0',
  '#required' => TRUE,
  '#datepicker_options' => array(
    'minDate' => 0,
  ),
);

minDate => 0 (Sets the min date to today's date)

minDate => -1 (Sets the min date to yesterday's date)

More info: http://api.jqueryui.com/datepicker/#option-minDate

  • HI Gaurav, Thanks for your replay i have deployed the code in my form,but the date picker in my form is not visible. I am using drupal 8, are there any changes to be made in drupal 8 – user3664791 Apr 21 '16 at 9:01
  • date_popup is not working in drupal 8 ??? – user3664791 Apr 21 '16 at 9:47
0
    $form['oneway']['from_date'] = array(
      '#title' => t('From Date'),
      '#type' => 'datetime',
      '#date_format' => 'Y-m-d',
      '#date_year_range' => '-80:0',
      '#required' => TRUE,
      '#attributes' => [
        'min' =>  \Drupal::service('date.formatter')->format(REQUEST_TIME, 'custom', 'Y-m-d'),
    ],
    );

date_popup is not going to work in drupal 8.x, use datetime

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.