Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 - datetime picker - combine form types into one

I am looking to create a re-usable datetime picker in symfony2. The idea is it will consist of 3 separate input parameters. I will update the question with complete info so other people can use my findings.

{text input} {select hour} {select time}

The question is how do I create a custom re-usable form that combines 3 inputs into one.

I have attached a screenshot to give an idea of what im trying to achive

enter image description here

the symfony docs
http://symfony.com/doc/current/cookbook/form/create_custom_field_type.html#creating-a-template-for-the-field

like image 371
Robbo_UK Avatar asked Jul 23 '13 09:07

Robbo_UK


2 Answers

You can simply use the jquery.datetime picker to show a datetime picker or just one of them(date or time).

i recently made on one of my website.

$builder->add('dateheure', 'datetime', array('date_widget' => "single_text", 'time_widget' => "single_text"));

and call jquery, datetime css and js on your page:

<link rel="stylesheet" type="text/css" href="jquery.datetimepicker.css"/ >
<script src="jquery.js"></script>
<script src="jquery.datetimepicker.js"></script>

and then active datetimepicker on your fields:

$(function(){
    $("#form_dateheure input").each(function(){
        $(this).attr("readonly","readonly");
    });
    $('#form_dateheure_date').datetimepicker({
        format: "Y-m-d",
        timepicker: false,
        datepicker: true,
    });
    $('#form_dateheure_time').datetimepicker({
        format: "H:i",
        timepicker: true,
        datepicker: false,
        step:5
    });
});
like image 197
Fabrice Kabongo Avatar answered Oct 19 '22 13:10

Fabrice Kabongo


As a example you can see to DateTime field. Check the source code.

Broadly speaking, first create the Custom Form Type, which when you can add to your forms. As example

class DateTimeType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('date', 'text');
        $builder->add('hour', 'choice', array(...));
        $builder->add('minute', 'choice', array(...));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

    public function getParent()
    {
        return 'form';
    }

    public function getName()
    {
        return 'date_time';
    }
}

Second add Data Transformer to it, which will transform your html data from 3 field into one DateTime object.

like image 25
Alexey B. Avatar answered Oct 19 '22 13:10

Alexey B.