<?php
/**
* Created by PhpStorm.
* User: frup64362
* Date: 09/08/2016
* Time: 09:39
*/
namespace App\EventListener;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\PropertyAccess\PropertyAccess;
class AddDiffusionFieldListener implements EventSubscriberInterface
{
public function __construct(private readonly string $propertyPathToAction = "")
{
}
public static function getSubscribedEvents()
{
return [FormEvents::PRE_SET_DATA => 'preSetData', FormEvents::PRE_SUBMIT => 'preSubmit'];
}
private function addSousActionForm($form, $action_id)
{
$formOptions = ['class' => \App\Entity\RefSousAction::class, 'multiple' => true, 'required' => false, 'empty_data' => null, 'query_builder' => fn(EntityRepository $er) => $er->createQueryBuilder('u')
->innerJoin('u.idAction', 'id_action')
->where('id_action.idAction IN (:idAction)')
->setParameter(':idAction', $action_id)
->orderBy('u.idSousAction', 'ASC'), 'choice_label' => 'libelleSousActionLong'];
$form->add('SousActions', EntityType::class, $formOptions);
}
public function preSetData(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
return;
}
$accessor = PropertyAccess::createPropertyAccessor();
$action = $accessor->getValue($data, $this->propertyPathToAction);
$action_id = ($action) ? $action->getIdAction() : null;
$this->addSousActionForm($form, $action_id);
}
public function preSubmit(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
$idActon = $data['Action'];
if ($idActon)
$this->addSousActionForm($form, $idActon);
}
}