<?php
namespace App\Form\EventListener;
use App\Entity\AnneeAcademique;
use App\Entity\Ue;
use App\Entity\UeEct;
use App\Repository\UeEctRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class AddEctFieldListener implements EventSubscriberInterface
{
private UeEctRepository $ueEctRepository;
public function __construct(UeEctRepository $ueEctRepository)
{
$this->ueEctRepository = $ueEctRepository;
}
public static function getSubscribedEvents(): array
{
return [
FormEvents::POST_SUBMIT => 'onPostSubmit',
];
}
public function onPostSubmit(FormEvent $event)
{
$ects = [];
$form = $event->getForm();
$parent = $form->getParent();
/** @var AnneeAcademique $academique */
$academique = $parent->get('academique')->getData();
/** @var Ue $ue */
$ue = $parent->get('ue')->getData();
if ($academique !== null) {
$ects = $this->ueEctRepository->findEctsByUe($ue, $academique);
} else {
$ects = $this->ueEctRepository->findEctsByUe($ue, null);
}
$parent->add('ueEct', EntityType::class, [
'class' => UeEct::class,
'attr' => [
'data-controller' => 'tom-select',
'required' => true
],
'label' => 'entity.ecue.long',
'placeholder' => '-- choisir une option --',
'choices' => $ects,
'auto_initialize' => false,
'choice_label' => function (UeEct $ect) {
return $ect->getEcue();
}
]);
}
}