src\Form\Type\LastDayOfMonthType.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\Form\Type;
  3. use Symfony\Component\Form\AbstractType;
  4. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  5. use Symfony\Component\Form\FormBuilderInterface;
  6. use Symfony\Component\Form\FormEvent;
  7. use Symfony\Component\Form\FormEvents;
  8. use Symfony\Component\OptionsResolver\OptionsResolver;
  9. class LastDayOfMonthType extends AbstractType
  10. {
  11.     public function configureOptions(OptionsResolver $resolver)
  12.     {
  13.         $resolver->setDefaults([
  14.             'empty_data' => ''// set a default value for the empty data
  15.             'choices' => $this->getLastDaysOfMonthChoices(),
  16.             'choice_label' => function ($value$key$index) {
  17.                 if (null === $value) {
  18.                     return 'Sans code';
  19.                 }
  20.                 return $value->format('d/m');
  21.             },
  22.             'choice_value' => function ($value) {
  23.                 if (null === $value) {
  24.                     return '';
  25.                 }
  26.                 return $value->format('Y-m-d');
  27.             },
  28.             'compound' => false,
  29.             'invalid_message' => 'Invalid datetime format. Expected "Y-m-d".',
  30.             'placeholder' => 'Sans code',
  31.             'required' => false,
  32.         ]);
  33.     }
  34.     private function getLastDaysOfMonthChoices()
  35.     {
  36.         $choices = ['Sans code' => null];
  37.         $now = new \DateTime();
  38.         for ($month 1$month <= 12; ++$month) {
  39.             $lastDay = (int) date('t'strtotime($now->format("Y-$month-01")));
  40.             $date = new \DateTime(sprintf('%d-%02d-%02d'$now->format('Y'), $month$lastDay));
  41.             $choices[$date->format('Y-m-d')] = $date;
  42.         }
  43.         return $choices;
  44.     }
  45.     public function buildForm(FormBuilderInterface $builder, array $options)
  46.     {
  47.         // Add a check to see if the date value is within the available choices
  48.         $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($options) {
  49.             $form $event->getForm();
  50.             $data $event->getData();
  51.             if ($data instanceof \DateTimeInterface && !array_key_exists($data->format('Y-m-d'), $options['choices'])) {
  52.                 $options['choices'][$data->format('Y-m-d')] = $data;
  53.                 $form->getParent()->add($form->getName(), self::class, $options);
  54.             }
  55.         });
  56.     }
  57.     public function getParent()
  58.     {
  59.         return ChoiceType::class;
  60.     }
  61. }