vendor/symfony/ux-autocomplete/src/Form/AutocompleteEntityTypeSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\UX\Autocomplete\Form;
  11. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\Form\FormEvent;
  14. use Symfony\Component\Form\FormEvents;
  15. /**
  16.  * Helps transform ParentEntityAutocompleteType into a EntityType that will not load all options.
  17.  *
  18.  * @internal
  19.  */
  20. final class AutocompleteEntityTypeSubscriber implements EventSubscriberInterface
  21. {
  22.     public function __construct(
  23.         private ?string $autocompleteUrl null
  24.     ) {
  25.     }
  26.     public function preSetData(FormEvent $event)
  27.     {
  28.         $form $event->getForm();
  29.         $data $event->getData() ?: [];
  30.         $options $form->getConfig()->getOptions();
  31.         $options['compound'] = false;
  32.         $options['choices'] = is_iterable($data) ? $data : [$data];
  33.         // pass to AutocompleteChoiceTypeExtension
  34.         $options['autocomplete'] = true;
  35.         $options['autocomplete_url'] = $this->autocompleteUrl;
  36.         unset($options['searchable_fields'], $options['security'], $options['filter_query']);
  37.         $form->add('autocomplete'EntityType::class, $options);
  38.     }
  39.     public function preSubmit(FormEvent $event)
  40.     {
  41.         $data $event->getData();
  42.         $form $event->getForm();
  43.         $options $form->get('autocomplete')->getConfig()->getOptions();
  44.         if (!isset($data['autocomplete']) || '' === $data['autocomplete']) {
  45.             $options['choices'] = [];
  46.         } else {
  47.             $options['choices'] = $options['em']->getRepository($options['class'])->findBy([
  48.                 $options['id_reader']->getIdField() => $data['autocomplete'],
  49.             ]);
  50.         }
  51.         // reset some critical lazy options
  52.         unset($options['em'], $options['loader'], $options['empty_data'], $options['choice_list'], $options['choices_as_values']);
  53.         $form->add('autocomplete'EntityType::class, $options);
  54.     }
  55.     public static function getSubscribedEvents(): array
  56.     {
  57.         return [
  58.             FormEvents::PRE_SET_DATA => 'preSetData',
  59.             FormEvents::PRE_SUBMIT => 'preSubmit',
  60.         ];
  61.     }
  62. }