src/EventSubscriber/DateTypeSubscriber.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\Form\FormEvent;
  5. use Symfony\Component\Form\FormEvents;
  6. use Symfony\Component\Form\Extension\Core\Type\DateType;
  7. class DateTypeSubscriber implements EventSubscriberInterface
  8. {
  9.     public static function getSubscribedEvents(): array
  10.     {
  11.         return [
  12.             FormEvents::PRE_SUBMIT => 'preSubmit',
  13.         ];
  14.     }
  15.     public function preSubmit(FormEvent $event): void
  16.     {
  17.         $data $event->getData();
  18.         if (is_array($data)) {
  19.             foreach ($data as $key => $value) {
  20.                 $formConfig $event->getForm()->get($key)->getConfig();
  21.                 if ($formConfig->getType()->getInnerType() instanceof DateType) {
  22.                     $data[$key] = $this->formatDate($value);
  23.                 }
  24.             }
  25.             $event->setData($data);
  26.         }
  27.     }
  28.     /**
  29.      * convert from dd/mm/yyyy to yyyy-mm-dd
  30.      */
  31.     private function formatDate($inputDate): string
  32.     {
  33.         $parts explode('/'$inputDate);
  34.         return $parts[2] . '-' $parts[1] . '-' $parts[0];
  35.     }
  36. }