<?php
namespace App\Form\EventListener;
use App\Entity\AnneeAcademique;
use App\Entity\NiveauFiliere;
use App\Entity\Ue;
use App\Repository\AffectationUeEcueRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class AddUeFieldListener implements EventSubscriberInterface
{
private AffectationUeEcueRepository $ueEcueRepository;
private AddEctFieldListener $addEctFieldListener;
public function __construct(AffectationUeEcueRepository $ueEcueRepository, AddEctFieldListener $addEctFieldListener)
{
$this->ueEcueRepository = $ueEcueRepository;
$this->addEctFieldListener = $addEctFieldListener;
}
public static function getSubscribedEvents(): array
{
return [
FormEvents::POST_SUBMIT => 'onPostSubmit',
];
}
public function onPostSubmit(FormEvent $event)
{
$ues = [];
$form = $event->getForm();
$parent = $form->getParent();
/** @var AnneeAcademique $academique */
$academique = $parent->get('academique')->getData();
/** @var NiveauFiliere $niveauFiliere */
$niveauFiliere = $form->getData();
if ($academique != null && $niveauFiliere != null) {
$affectations = $this->ueEcueRepository->getByYear(
$academique,
$niveauFiliere
);
foreach ($affectations as $affectation) {
$ues[] = $affectation->getUe();
}
}
// create builder, so we can add the listener to ue field
$builder = $parent
->getConfig()
->getFormFactory()
->createNamedBuilder('ue', EntityType::class, null, [
'class' => Ue::class,
'attr' => [
'data-controller' => 'tom',
'required' => true
],
'placeholder' => '-- choisir une option --',
'choices' => $ues,
'auto_initialize' => false
])
->addEventSubscriber($this->addEctFieldListener);
$parent->add($builder->getForm());
}
}