<?php
namespace App\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
class LastDayOfMonthType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'empty_data' => '', // set a default value for the empty data
'choices' => $this->getLastDaysOfMonthChoices(),
'choice_label' => function ($value, $key, $index) {
if (null === $value) {
return 'Sans code';
}
return $value->format('d/m');
},
'choice_value' => function ($value) {
if (null === $value) {
return '';
}
return $value->format('Y-m-d');
},
'compound' => false,
'invalid_message' => 'Invalid datetime format. Expected "Y-m-d".',
'placeholder' => 'Sans code',
'required' => false,
]);
}
private function getLastDaysOfMonthChoices()
{
$choices = ['Sans code' => null];
$now = new \DateTime();
for ($month = 1; $month <= 12; ++$month) {
$lastDay = (int) date('t', strtotime($now->format("Y-$month-01")));
$date = new \DateTime(sprintf('%d-%02d-%02d', $now->format('Y'), $month, $lastDay));
$choices[$date->format('Y-m-d')] = $date;
}
return $choices;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Add a check to see if the date value is within the available choices
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($options) {
$form = $event->getForm();
$data = $event->getData();
if ($data instanceof \DateTimeInterface && !array_key_exists($data->format('Y-m-d'), $options['choices'])) {
$options['choices'][$data->format('Y-m-d')] = $data;
$form->getParent()->add($form->getName(), self::class, $options);
}
});
}
public function getParent()
{
return ChoiceType::class;
}
}