<?php
namespace App\EventSubscriber\Form;
use App\Entity\Adresse;
use App\Entity\AdresseType;
use App\Entity\Reseau;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Validator\Constraints\NotNull;
class AddAdresseCongresSubscriber implements EventSubscriberInterface
{
/**
* @var EntityManagerInterface
*/
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->adresseCongres = [AdresseType::ADRESSE_CONGRES_NATIONAUX, AdresseType::ADRESSE_CONGRES_REGIONAUX];
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents(): array
{
return [
FormEvents::PRE_SET_DATA => 'preSetData',
FormEvents::PRE_SUBMIT => 'preSubmit',
];
}
public function preSetData(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
$adresseType = $data->getAdresseType();
if($adresseType){
$this->addField($form, $adresseType);
}
}
public function preSubmit(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if(array_key_exists("adresseType", $data)) {
$adresseTypeID = $data["adresseType"];
$adresseType = $this->entityManager->getRepository(AdresseType::class)->findOneBy(['id'=>$adresseTypeID]);
if($adresseType){
$this->addField($form, $adresseType);
}else{
$form->get('adresseType')->addError(new FormError('Type d\'adresse invalide'));
}
}
}
private function addField($form, $adresseType)
{
if (in_array($adresseType->getCode(), $this->adresseCongres)) {
$form->add('visibleForVM');
$form->add('dateDVisible', DateType::class,
array(
"required" => false,
"label" => "Date de début de visibilité",
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
// 2. Disable HTML5 option
// https://ourcodeworld.com/articles/read/1182/how-to-solve-symfony-5-exception-cannot-use-the-format-option-of-symfony-component-form-extension-core-type-datetype-when-the-html5-option-is-enabled
'html5' => false,
"attr" =>
array(
"placeholder" => "Date de début de visibilité",
"class" => "datetimepicker",
)
)
);
$form->add('dateFVisible', DateType::class,
array(
"required" => false,
"label" => "Date de fin de visibilité",
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
// 2. Disable HTML5 option
// https://ourcodeworld.com/articles/read/1182/how-to-solve-symfony-5-exception-cannot-use-the-format-option-of-symfony-component-form-extension-core-type-datetype-when-the-html5-option-is-enabled
'html5' => false,
"attr" =>
array(
"placeholder" => "Date de fin de visibilité",
"class" => "datetimepicker",
)
)
);
}else{
$form->remove('visibleForVM');
$form->remove('dateDVisible');
$form->remove('dateFVisible');
}
}
}