Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@Asenar Asenar commented Feb 2, 2021

Thanks for the timesaving :) 

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