<?php
namespace App\Form\EventSubscriber;
use App\Entity\ContactSheet\PriorityContact;
use App\Form\ContactSheet\InterruptionContactsType;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class ContactSheetEventSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
FormEvents::PRE_SET_DATA => 'addInterruptionContactsField',
FormEvents::POST_SUBMIT => 'addInterruptionContactsField',
];
}
public function addInterruptionContactsField(FormEvent $event): void
{
$priorityContacts = $event->getData();
if ($priorityContacts instanceof Collection) {
$users = $this->getUsersFromPriorityContacts($priorityContacts);
$event->getForm()->getParent()->add('interruptionContacts', InterruptionContactsType::class, [
'users' => $users,
'label' => false,
]);
}
}
protected function getUsersFromPriorityContacts(Collection $priorityContacts): array
{
$users = [];
/** @var PriorityContact $priorityContact */
foreach ($priorityContacts as $priorityContact) {
if (!in_array($priorityContact->getUser(), $users)) {
$users[] = $priorityContact->getUser();
}
}
return $users;
}
}