Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

forms - How to display a month-year dropdown in Symfony2

In my application, the user hsa to give a date by only selecting a month and a year in two dropdown lists. How can I achieve that?

Here is what I've tried so far :

In my Form :

$builder->add('date1', 'date', array(
 'widget'      => 'choice',
 'empty_value' => '',
 'format'      => 'MMMM-yyyy',
 'input'       => 'datetime',
 'years'       => range(date('Y'), date('Y') - 30, -1)
)

which actually works and displays it exactly as I want but when validating the form, I get an error :

This value is not valid

A screenshot of the wanted result :

Screenshot

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Example for credit card expiration date:

$builder->add('expirationDate', 'date', array(
 'label' => 'Expiration date',
 'widget' => 'choice',
 'empty_value' => array('year' => 'Year', 'month' => 'Month', 'day' => 'Day'),
 'format' => 'dd-MM-yyyy',
 'input' => 'string',
 'data' => date('Y-m-d'),
 'years' => range(date('Y'), date('Y') + 10),
));

Then you must render this field manually.

Your form's twig template:

{{ form_row(form.expirationDate, {'date_pattern': '<span style="display: none;">{{ day }}</span> {{ month }} <span class="delim">&#47;</span> {{ year }}'}) }}

Overriding date_pattern will hide day select. You will get month / year format.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...