Creating a credit card month/year form field input in Symfony 2.5

Creating a credit card month/year input can be accomplished with a single database field but Symfony is smart enough to create multiple pull downs for each.  It is NOT smart enough to not require the programmer to exclude the “day” value.  So, what do you do?  There are many workarounds, including using some post rendering JQuery nujitsu, but that’s crazy.  Still, you have to include the “d” in the date’s format or you will get an error.

Since the day will be ignored, you have Symfony render the field then hide it with CSS.  Not as graceful as a solution you’d expect.  There are ways to create customized inputs, but something this simple I found this is a good enough solution in most cases.

Here’s how you add the credit card expiration date field to your form builder, which is usually created in the entity’s “form type”.


->add(
'ccExpirationDate',
'date',
array(
'format' =>'MMM-yyyy  d',
'years' => range(date('Y'), date('Y')+12),
'days' => array(1),
'empty_value' => array('year' => 'Select Year', 'month' => 'Select Month', 'day' => false)
)
)

// Example of outputting the form field in the TWIG template

{{  form_widget( form.payment.ccExpirationDate.day, { ‘attr’: { ‘style’: ‘display:none’ } } )  }}

Disclaimer — this was an idea used in a few different sites, not my original solution but I put it here because I am sure I’ll need to find a way to do this again.

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *