1

I am using following code to build the select box for Month and year

$form['billing']['expiry_db'] = array(
    '#type' => 'date_select',
    '#title' => t('Expiry Date'),
    '#default_value' => date('m Y'),
    '#date_format' => 'm Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '0:+20',
    '#required' => TRUE,
    '#prefix' => '<div class="field-wrapper-w1">'
);

I am passing following value in database

$form_state['values']['billing']['expiry_db']['month']

and

$form_state['values']['billing']['expiry_db']['year']

but it is only showing value '2' for month and value '2' for year. However I am selecting month 'December' which has value '12' in HTML. Please help

1 Answer 1

1

The value for #default_value must have the date() format "Y-m-d H:i:s"; the value returned in $form_state is a string.

In your case, the code you should use is the following one.

  $form['billing']['expiry_db'] = array(
    '#type' => 'date_select',
    '#title' => t('Expiry Date'),
    '#default_value' => date('Y-m-d H:i:s'),
    '#date_format' => 'm Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '0:+20',
    '#required' => TRUE,
    '#prefix' => '<div class="field-wrapper-w1">',
  );

If the form has #tree set to TRUE, then $form_state['values']['billing']['expiry_db'] a string such as '2020-05' for May, 2020.

As far as I can see, the value of #date_format is only used to understand which components of a date must be returned, but the format of the returned value is always the same. Changing #date_format to 'Y-H:s' the returned value is '2020 00:00'. In you case, the code to get the month, and the year is the following one.

list($year, $month) = explode('-', $form_state['values']['billing']['expiry_db']);

References

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.