Symfony2 Forms have a rich set of field types and many defined widgets for rendering fields. But still we may need a different representation of a field. For example, in a web application of today we cannot think of a date field without a datepicker.
Symfony2 Forms don’t have any built in widget for rendering a date field with a datepicker. But, Symfony Form’s customization options are so flexible that, actually there is nothing to be worry about. Just in few minutes, using a simple trick, we can turn our date filed into a datepicker. In this post, I am going to share the trick with an example.
To demonstrate this idea, first we need a rendered Symfony Form with a date field. If you don’t have it already, please quickly go through Step 1 and Step 2 of previous post about Symfony2 Forms. We’ll now discuss about how to render the date field with a datepicker instead of 3 dropdowns. It’s just 3 tasks.
- Download this library from github.
- Place it in
Resources/public/plugins/directory of your Bundle or in
- Include the
css/datepicker.cssfiles of this plugin in your layout.
See how to do it if you’ve any confusion.
Step 2. Render the date field as text input
Just add the following options to date filed –
// ->add('dueDate', 'date') ->add('dueDate', 'date', ['widget' => 'single_text', 'format' => 'dd-MM-yyyy'])
Now the dueDate field will be rendered as a text input. And, after submission of the form, Symfony will expect the date as
dd-MM-yyyy (this is the default) format. For more information on valid formats, see Date/Time Format Syntax.
Step 3. Instantiate datepicker with this text input
data-attributes for instantiating and configuring datepicker on a target element. Let’s set proper attributes on our dueDate field –
// ->add('dueDate', 'date', ['widget' => 'single_text', 'format' => 'dd-MM-yyyy']) ->add('dueDate', 'date', [ 'widget' => 'single_text', 'format' => 'dd-MM-yyyy', 'attr' => [ 'class' => 'form-control input-inline datepicker', 'data-provide' => 'datepicker', 'data-date-format' => 'dd-mm-yyyy' ] ]
Here, using the
data-provide attribute we are instructing to instantiate a datepicker on this text field and using
data-date-format to set the date format to Symfony’s expected pattern. If you change the date format, remember to change
data-date-format attribute and
format options respectively. Check the full list of configuration options. You’ll surely be amazed with the completeness of option set.
If your datepicker library do not provide data-attributes like this example, you can use the
We’re Done! It was easy, right?