Skip to content

Instantly share code, notes, and snippets.

@treetop1500
Last active September 10, 2022 08:52
Show Gist options
  • Save treetop1500/cda62c1e2e3bfdb4e015645ec88112b8 to your computer and use it in GitHub Desktop.
Save treetop1500/cda62c1e2e3bfdb4e015645ec88112b8 to your computer and use it in GitHub Desktop.
Symfony3 Form Extension for use with Flatpickr javascript date/time pickers
<?php
namespace MyBundle\Form\Extension;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
/**
* Class FlatpickrDateTimeType
* @package MyBundle\Form\Extension
*/
class FlatpickrDateTimeType extends AbstractType
{
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'widget' => 'single_text',
'attr' => array(
'placeholder' => 'Select a date...',
'class' => "flatpickr datetime",
),
));
}
/**
* @return mixed
*/
public function getParent()
{
return DateTimeType::class;
}
}
<?php
namespace MyBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use MyBundle\Form\Extension\FlatpickrDateTimeType;
/**
* Class PostType
* @package MyBundle\Form
*/
class PostType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add("publishDate", FlatPickrDateTimeType::class, array(
'label' => 'Publish Date',
'required' => false,
))
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MyBundle\Entity\Post',
));
}
}
{% extends 'base.html.twig' %}
{% block stylesheets %}
{{ parent() }}
<link rel="stylesheet" href="{{ asset('bower_components/flatpickr/dist/flatpickr.min.css') }}" />
{% endblock %}
{% block body %}
{{ form_start(edit_form) }}
{{ form_row(edit_form.publishDate) }}
{{ form_rest(edit_form) }}
{{ form_end(edit_form) }}
{% endblock %}
{% block javascripts %}
{{ parent() }}
<script src="{{ asset('bower_components/flatpickr/dist/flatpickr.min.js') }}"></script>
<script type="text/javascript">
flatpickr(".flatpickr.datetime", {
enableTime: true
});
</script>
{% endblock %}
@Asenar
Copy link

Asenar commented Feb 2, 2021

Thanks for the timesaving :) 

@DamienL47
Copy link

MERCIIIII, je cherches depuis tellement longtemps et enfin je trouve ici ce que je voulais encore un grand merci

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment