src/Form/EventListener/Global/AddNameFieldSubscriber.php line 28

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Form\EventListener\Global;
  4. use App\Form\FormHelper;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\Form\Extension\Core\Type\TextType;
  7. use Symfony\Component\Form\FormEvent;
  8. use Symfony\Component\Form\FormEvents;
  9. class AddNameFieldSubscriber extends FormHelper implements EventSubscriberInterface
  10. {
  11.     public function __construct(
  12.         private ?string $label 'app.global.fields.name',
  13.         private string $placeholder self::PLACEHOLDER_SAME_AS_LABEL,
  14.         private bool $readOnly false,
  15.         private string $class '',
  16.     ) {
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return [FormEvents::PRE_SET_DATA => 'preSetData'];
  21.     }
  22.     public function preSetData(FormEvent $event): void
  23.     {
  24.         $entity $event->getData();
  25.         $mapped true;
  26.         $attr = ['class' => $this->class];
  27.         if (false === \is_array($entity) && null !== $entity && null !== $entity->getId()) {
  28.             $attr['value'] = $entity->getName();
  29.             if (true === $this->readOnly) {
  30.                 $attr['readonly'] = 'readonly';
  31.                 $mapped false;
  32.             }
  33.         }
  34.         $event->getForm()->add('name'TextType::class, $this->getTextParameters($this->label$this->placeholdertruecompact('attr''mapped')));
  35.     }
  36. }