Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating date field with only month and year - Drupal

I am creating a credit card form in Drupal. I need a date select field where users can select their credit card expiry date, which consists of only Month and Year -No Day.

The Drupal form #type 'date' produces a date chooser, which has day-month-year option. I just need month-year. Any help?

like image 471
Sparky Avatar asked Mar 08 '11 07:03

Sparky


2 Answers

Using the Date API module (part of the Date module), you can do something like this....

<?php
$form['payment_expirationDate'] = array(
    '#type' => 'date_select',
    '#title' => t('Expiration Date:'),
    '#date_format' => 'm-Y',
    '#default_value' => $expirationDate,
    '#date_year_range' => '-1:+10',
    '#required' => TRUE,
    '#date_label_position' => 'within'
 ); 
?>

The date_select type will give you select box form elements for your field. And the #date_format array key allows you to use a PHP date format string to control what select boxes appear and what goes inside them.

like image 166
Adam Kalsey Avatar answered Dec 07 '22 20:12

Adam Kalsey


Go for two select boxes and pre populate the fields with month and years!

'#type' => 'select', '#options' => array( '1' => 'January', '2' => 'February', . . . '12' => 'December', ),

Same way for the years. You can generate the year array using simple php code and then use it in the option instead of giving all the years manually!

like image 43
srinath Avatar answered Dec 07 '22 19:12

srinath