<?php
namespace App\EventSubscriber\Form;
use App\Entity\Reseau;
use App\Entity\User;
use Doctrine\ORM\EntityRepository;
use Lexik\Bundle\FormFilterBundle\Filter\Form\Type\EntityFilterType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class AddReseauFieldByDotation implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
FormEvents::PRE_SET_DATA => 'preSetData',
FormEvents::PRE_SUBMIT => 'preSubmit',
];
}
public function preSetData(FormEvent $event)
{
$form = $event->getForm();
$dotation = $form->get('dotation')->getData();
$this->addField($form, $dotation);
}
public function preSubmit(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if (array_key_exists("dotation", $data)) {
$dotation = $data["dotation"];
$this->addField($form, $dotation);
}
}
private function addField(
$form,
$dotation
)
{
$form->add('reseau', EntityType::class,
array(
'class' => Reseau::class,
'choice_label' => 'libelle',
'multiple' => true,
'placeholder' => 'app.tous',
'empty_data' => null,
'query_builder' => function (
EntityRepository $er
) use (
$dotation
) {
return $er->createQueryBuilder('r')
->innerJoin('r.dotations', 'dots')
->where('dots.id in (:dotation)')
->setParameter('dotation', $dotation)
->orderBy('r.libelle', 'ASC');
},
'required' => false,
'attr' =>
array(
'label' => 'Réseau',
),
)
);
}
}