<?php
declare(strict_types=1);
namespace App\Form\EventListener\Global;
use App\Form\FormHelper;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class AddCodeFieldSubscriber extends FormHelper implements EventSubscriberInterface
{
public function __construct(
private string $label = 'app.global.fields.code',
private string $placeholder = self::PLACEHOLDER_SAME_AS_LABEL,
private bool $readOnly = true
) {
}
public static function getSubscribedEvents(): array
{
return [FormEvents::PRE_SET_DATA => 'preSetData'];
}
public function preSetData(FormEvent $event): void
{
$entity = $event->getData();
$mapped = true;
$attr = [];
if (null !== $entity && null !== $entity->getId()) {
$mapped = false;
$attr['value'] = $entity->getCode();
} else {
$attr['class'] = 'slug-destination solid';
}
if (true === $this->readOnly) {
$attr['readonly'] = 'readonly';
}
$event->getForm()->add('code', TextType::class, $this->getTextParameters($this->label, $this->placeholder, true, compact('attr', 'mapped')));
}
}