March 31, 2016

How to make symfony forms support datetime-local input type?

Starx’s Question:

Most of the browsers are dropping support for datetime and also datetime-local as a valid input type. As of the time of writing this question, there are more support for support for datetime-local than datetime(which is almost non-existent).

If you building forms using Symfony’s form builder, it supports datetime but not datetime-local. So how would you make symfony form builder accept datetime-local input type and keep the rest of the functionality of the input type same?

One way this problem can be solved is, if we can change the text of input type to say datetime-local which can be done by overwriting the DateTimeType and using that.

<?php

namespace AppBundleComponentFormExtensionCoreType;

use SymfonyComponentFormFormInterface;
use SymfonyComponentFormFormView;

class DateTimeType extends SymfonyComponentFormExtensionCoreTypeDateTimeType
{
    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['widget'] = $options['widget'];

        // Change the input to a HTML5 datetime input if
        //  * the widget is set to "single_text"
        //  * the format matches the one expected by HTML5
        //  * the html5 is set to true
        if ($options['html5'] && 'single_text' === $options['widget'] && self::HTML5_FORMAT === $options['format']) {
            $view->vars['type'] = 'datetime-local';
        }
    }

}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!