<?php
declare(strict_types=1);
namespace App\Form\EventListener\Franchise;
use App\Entity\Admin\MediaNameInterface;
use App\Entity\Franchise\Franchise;
use App\Entity\Franchise\Media;
use App\Form\Franchise\LogoType;
use App\Repository\Admin\MediaNameRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class AddMediaFieldSubscriber implements EventSubscriberInterface
{
public function __construct(
private MediaNameRepository $mediaNameRepository,
) {
}
public static function getSubscribedEvents(): array
{
return [FormEvents::PRE_SET_DATA => 'preSetData'];
}
public function preSetData(FormEvent $event): void
{
/** @var Franchise $franchise */
$franchise = $event->getData();
if (null !== $franchise && null !== $franchise->getId()) {
return;
}
if (0 === $franchise->getMedia()->count()) {
$media = new Media();
$mediaName = $this->mediaNameRepository->findOneByName(MediaNameInterface::MEDIA_NAME_LOGO);
$media->setMediaName($mediaName);
$franchise->addMedium($media);
}
$event->getForm()->add('media', CollectionType::class, [
'entry_type' => LogoType::class,
'entry_options' => ['label' => false],
]);
}
}