vendor/symfony/form/Extension/Core/Type/ChoiceType.php line 50

  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\Component\Form\Extension\Core\Type;
  11. use Symfony\Component\Form\AbstractType;
  12. use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
  13. use Symfony\Component\Form\ChoiceList\Factory\Cache\ChoiceAttr;
  14. use Symfony\Component\Form\ChoiceList\Factory\Cache\ChoiceFieldName;
  15. use Symfony\Component\Form\ChoiceList\Factory\Cache\ChoiceFilter;
  16. use Symfony\Component\Form\ChoiceList\Factory\Cache\ChoiceLabel;
  17. use Symfony\Component\Form\ChoiceList\Factory\Cache\ChoiceLoader;
  18. use Symfony\Component\Form\ChoiceList\Factory\Cache\ChoiceTranslationParameters;
  19. use Symfony\Component\Form\ChoiceList\Factory\Cache\ChoiceValue;
  20. use Symfony\Component\Form\ChoiceList\Factory\Cache\GroupBy;
  21. use Symfony\Component\Form\ChoiceList\Factory\Cache\PreferredChoice;
  22. use Symfony\Component\Form\ChoiceList\Factory\CachingFactoryDecorator;
  23. use Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface;
  24. use Symfony\Component\Form\ChoiceList\Factory\DefaultChoiceListFactory;
  25. use Symfony\Component\Form\ChoiceList\Factory\PropertyAccessDecorator;
  26. use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;
  27. use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView;
  28. use Symfony\Component\Form\ChoiceList\View\ChoiceListView;
  29. use Symfony\Component\Form\ChoiceList\View\ChoiceView;
  30. use Symfony\Component\Form\Exception\TransformationFailedException;
  31. use Symfony\Component\Form\Extension\Core\DataMapper\CheckboxListMapper;
  32. use Symfony\Component\Form\Extension\Core\DataMapper\RadioListMapper;
  33. use Symfony\Component\Form\Extension\Core\DataTransformer\ChoicesToValuesTransformer;
  34. use Symfony\Component\Form\Extension\Core\DataTransformer\ChoiceToValueTransformer;
  35. use Symfony\Component\Form\Extension\Core\EventListener\MergeCollectionListener;
  36. use Symfony\Component\Form\FormBuilderInterface;
  37. use Symfony\Component\Form\FormError;
  38. use Symfony\Component\Form\FormEvent;
  39. use Symfony\Component\Form\FormEvents;
  40. use Symfony\Component\Form\FormInterface;
  41. use Symfony\Component\Form\FormView;
  42. use Symfony\Component\OptionsResolver\Options;
  43. use Symfony\Component\OptionsResolver\OptionsResolver;
  44. use Symfony\Component\PropertyAccess\PropertyPath;
  45. use Symfony\Contracts\Translation\TranslatorInterface;
  46. class ChoiceType extends AbstractType
  47. {
  48.     private ChoiceListFactoryInterface $choiceListFactory;
  49.     private ?TranslatorInterface $translator;
  50.     public function __construct(ChoiceListFactoryInterface $choiceListFactory nullTranslatorInterface $translator null)
  51.     {
  52.         $this->choiceListFactory $choiceListFactory ?? new CachingFactoryDecorator(
  53.             new PropertyAccessDecorator(
  54.                 new DefaultChoiceListFactory()
  55.             )
  56.         );
  57.         $this->translator $translator;
  58.     }
  59.     public function buildForm(FormBuilderInterface $builder, array $options)
  60.     {
  61.         $unknownValues = [];
  62.         $choiceList $this->createChoiceList($options);
  63.         $builder->setAttribute('choice_list'$choiceList);
  64.         if ($options['expanded']) {
  65.             $builder->setDataMapper($options['multiple'] ? new CheckboxListMapper() : new RadioListMapper());
  66.             // Initialize all choices before doing the index check below.
  67.             // This helps in cases where index checks are optimized for non
  68.             // initialized choice lists. For example, when using an SQL driver,
  69.             // the index check would read in one SQL query and the initialization
  70.             // requires another SQL query. When the initialization is done first,
  71.             // one SQL query is sufficient.
  72.             $choiceListView $this->createChoiceListView($choiceList$options);
  73.             $builder->setAttribute('choice_list_view'$choiceListView);
  74.             // Check if the choices already contain the empty value
  75.             // Only add the placeholder option if this is not the case
  76.             if (null !== $options['placeholder'] && === \count($choiceList->getChoicesForValues(['']))) {
  77.                 $placeholderView = new ChoiceView(null''$options['placeholder']);
  78.                 // "placeholder" is a reserved name
  79.                 $this->addSubForm($builder'placeholder'$placeholderView$options);
  80.             }
  81.             $this->addSubForms($builder$choiceListView->preferredChoices$options);
  82.             $this->addSubForms($builder$choiceListView->choices$options);
  83.         }
  84.         if ($options['expanded'] || $options['multiple']) {
  85.             // Make sure that scalar, submitted values are converted to arrays
  86.             // which can be submitted to the checkboxes/radio buttons
  87.             $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($choiceList$options, &$unknownValues) {
  88.                 $form $event->getForm();
  89.                 $data $event->getData();
  90.                 // Since the type always use mapper an empty array will not be
  91.                 // considered as empty in Form::submit(), we need to evaluate
  92.                 // empty data here so its value is submitted to sub forms
  93.                 if (null === $data) {
  94.                     $emptyData $form->getConfig()->getEmptyData();
  95.                     $data $emptyData instanceof \Closure $emptyData($form$data) : $emptyData;
  96.                 }
  97.                 // Convert the submitted data to a string, if scalar, before
  98.                 // casting it to an array
  99.                 if (!\is_array($data)) {
  100.                     if ($options['multiple']) {
  101.                         throw new TransformationFailedException('Expected an array.');
  102.                     }
  103.                     $data = (array) (string) $data;
  104.                 }
  105.                 // A map from submitted values to integers
  106.                 $valueMap array_flip($data);
  107.                 // Make a copy of the value map to determine whether any unknown
  108.                 // values were submitted
  109.                 $unknownValues $valueMap;
  110.                 // Reconstruct the data as mapping from child names to values
  111.                 $knownValues = [];
  112.                 if ($options['expanded']) {
  113.                     /** @var FormInterface $child */
  114.                     foreach ($form as $child) {
  115.                         $value $child->getConfig()->getOption('value');
  116.                         // Add the value to $data with the child's name as key
  117.                         if (isset($valueMap[$value])) {
  118.                             $knownValues[$child->getName()] = $value;
  119.                             unset($unknownValues[$value]);
  120.                             continue;
  121.                         } else {
  122.                             $knownValues[$child->getName()] = null;
  123.                         }
  124.                     }
  125.                 } else {
  126.                     foreach ($data as $value) {
  127.                         if ($choiceList->getChoicesForValues([$value])) {
  128.                             $knownValues[] = $value;
  129.                             unset($unknownValues[$value]);
  130.                         }
  131.                     }
  132.                 }
  133.                 // The empty value is always known, independent of whether a
  134.                 // field exists for it or not
  135.                 unset($unknownValues['']);
  136.                 // Throw exception if unknown values were submitted (multiple choices will be handled in a different event listener below)
  137.                 if (\count($unknownValues) > && !$options['multiple']) {
  138.                     throw new TransformationFailedException(sprintf('The choices "%s" do not exist in the choice list.'implode('", "'array_keys($unknownValues))));
  139.                 }
  140.                 $event->setData($knownValues);
  141.             });
  142.         }
  143.         if ($options['multiple']) {
  144.             $messageTemplate $options['invalid_message'] ?? 'The value {{ value }} is not valid.';
  145.             $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use (&$unknownValues$messageTemplate) {
  146.                 // Throw exception if unknown values were submitted
  147.                 if (\count($unknownValues) > 0) {
  148.                     $form $event->getForm();
  149.                     $clientDataAsString \is_scalar($form->getViewData()) ? (string) $form->getViewData() : (\is_array($form->getViewData()) ? implode('", "'array_keys($unknownValues)) : \gettype($form->getViewData()));
  150.                     if (null !== $this->translator) {
  151.                         $message $this->translator->trans($messageTemplate, ['{{ value }}' => $clientDataAsString], 'validators');
  152.                     } else {
  153.                         $message strtr($messageTemplate, ['{{ value }}' => $clientDataAsString]);
  154.                     }
  155.                     $form->addError(new FormError($message$messageTemplate, ['{{ value }}' => $clientDataAsString], null, new TransformationFailedException(sprintf('The choices "%s" do not exist in the choice list.'$clientDataAsString))));
  156.                 }
  157.             });
  158.             // <select> tag with "multiple" option or list of checkbox inputs
  159.             $builder->addViewTransformer(new ChoicesToValuesTransformer($choiceList));
  160.         } else {
  161.             // <select> tag without "multiple" option or list of radio inputs
  162.             $builder->addViewTransformer(new ChoiceToValueTransformer($choiceList));
  163.         }
  164.         if ($options['multiple'] && $options['by_reference']) {
  165.             // Make sure the collection created during the client->norm
  166.             // transformation is merged back into the original collection
  167.             $builder->addEventSubscriber(new MergeCollectionListener(truetrue));
  168.         }
  169.         // To avoid issues when the submitted choices are arrays (i.e. array to string conversions),
  170.         // we have to ensure that all elements of the submitted choice data are NULL, strings or ints.
  171.         $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
  172.             $data $event->getData();
  173.             if (!\is_array($data)) {
  174.                 return;
  175.             }
  176.             foreach ($data as $v) {
  177.                 if (null !== $v && !\is_string($v) && !\is_int($v)) {
  178.                     throw new TransformationFailedException('All choices submitted must be NULL, strings or ints.');
  179.                 }
  180.             }
  181.         }, 256);
  182.     }
  183.     public function buildView(FormView $viewFormInterface $form, array $options)
  184.     {
  185.         $choiceTranslationDomain $options['choice_translation_domain'];
  186.         if ($view->parent && null === $choiceTranslationDomain) {
  187.             $choiceTranslationDomain $view->vars['translation_domain'];
  188.         }
  189.         /** @var ChoiceListInterface $choiceList */
  190.         $choiceList $form->getConfig()->getAttribute('choice_list');
  191.         /** @var ChoiceListView $choiceListView */
  192.         $choiceListView $form->getConfig()->hasAttribute('choice_list_view')
  193.             ? $form->getConfig()->getAttribute('choice_list_view')
  194.             : $this->createChoiceListView($choiceList$options);
  195.         $view->vars array_replace($view->vars, [
  196.             'multiple' => $options['multiple'],
  197.             'expanded' => $options['expanded'],
  198.             'preferred_choices' => $choiceListView->preferredChoices,
  199.             'choices' => $choiceListView->choices,
  200.             'separator' => '-------------------',
  201.             'placeholder' => null,
  202.             'choice_translation_domain' => $choiceTranslationDomain,
  203.             'choice_translation_parameters' => $options['choice_translation_parameters'],
  204.         ]);
  205.         // The decision, whether a choice is selected, is potentially done
  206.         // thousand of times during the rendering of a template. Provide a
  207.         // closure here that is optimized for the value of the form, to
  208.         // avoid making the type check inside the closure.
  209.         if ($options['multiple']) {
  210.             $view->vars['is_selected'] = function ($choice, array $values) {
  211.                 return \in_array($choice$valuestrue);
  212.             };
  213.         } else {
  214.             $view->vars['is_selected'] = function ($choice$value) {
  215.                 return $choice === $value;
  216.             };
  217.         }
  218.         // Check if the choices already contain the empty value
  219.         $view->vars['placeholder_in_choices'] = $choiceListView->hasPlaceholder();
  220.         // Only add the empty value option if this is not the case
  221.         if (null !== $options['placeholder'] && !$view->vars['placeholder_in_choices']) {
  222.             $view->vars['placeholder'] = $options['placeholder'];
  223.         }
  224.         if ($options['multiple'] && !$options['expanded']) {
  225.             // Add "[]" to the name in case a select tag with multiple options is
  226.             // displayed. Otherwise only one of the selected options is sent in the
  227.             // POST request.
  228.             $view->vars['full_name'] .= '[]';
  229.         }
  230.     }
  231.     public function finishView(FormView $viewFormInterface $form, array $options)
  232.     {
  233.         if ($options['expanded']) {
  234.             // Radio buttons should have the same name as the parent
  235.             $childName $view->vars['full_name'];
  236.             // Checkboxes should append "[]" to allow multiple selection
  237.             if ($options['multiple']) {
  238.                 $childName .= '[]';
  239.             }
  240.             foreach ($view as $childView) {
  241.                 $childView->vars['full_name'] = $childName;
  242.             }
  243.         }
  244.     }
  245.     public function configureOptions(OptionsResolver $resolver)
  246.     {
  247.         $emptyData = function (Options $options) {
  248.             if ($options['expanded'] && !$options['multiple']) {
  249.                 return null;
  250.             }
  251.             if ($options['multiple']) {
  252.                 return [];
  253.             }
  254.             return '';
  255.         };
  256.         $placeholderDefault = function (Options $options) {
  257.             return $options['required'] ? null '';
  258.         };
  259.         $placeholderNormalizer = function (Options $options$placeholder) {
  260.             if ($options['multiple']) {
  261.                 // never use an empty value for this case
  262.                 return null;
  263.             } elseif ($options['required'] && ($options['expanded'] || isset($options['attr']['size']) && $options['attr']['size'] > 1)) {
  264.                 // placeholder for required radio buttons or a select with size > 1 does not make sense
  265.                 return null;
  266.             } elseif (false === $placeholder) {
  267.                 // an empty value should be added but the user decided otherwise
  268.                 return null;
  269.             } elseif ($options['expanded'] && '' === $placeholder) {
  270.                 // never use an empty label for radio buttons
  271.                 return 'None';
  272.             }
  273.             // empty value has been set explicitly
  274.             return $placeholder;
  275.         };
  276.         $compound = function (Options $options) {
  277.             return $options['expanded'];
  278.         };
  279.         $choiceTranslationDomainNormalizer = function (Options $options$choiceTranslationDomain) {
  280.             if (true === $choiceTranslationDomain) {
  281.                 return $options['translation_domain'];
  282.             }
  283.             return $choiceTranslationDomain;
  284.         };
  285.         $resolver->setDefaults([
  286.             'multiple' => false,
  287.             'expanded' => false,
  288.             'choices' => [],
  289.             'choice_filter' => null,
  290.             'choice_loader' => null,
  291.             'choice_label' => null,
  292.             'choice_name' => null,
  293.             'choice_value' => null,
  294.             'choice_attr' => null,
  295.             'choice_translation_parameters' => [],
  296.             'preferred_choices' => [],
  297.             'group_by' => null,
  298.             'empty_data' => $emptyData,
  299.             'placeholder' => $placeholderDefault,
  300.             'error_bubbling' => false,
  301.             'compound' => $compound,
  302.             // The view data is always a string or an array of strings,
  303.             // even if the "data" option is manually set to an object.
  304.             // See https://github.com/symfony/symfony/pull/5582
  305.             'data_class' => null,
  306.             'choice_translation_domain' => true,
  307.             'trim' => false,
  308.             'invalid_message' => 'The selected choice is invalid.',
  309.         ]);
  310.         $resolver->setNormalizer('placeholder'$placeholderNormalizer);
  311.         $resolver->setNormalizer('choice_translation_domain'$choiceTranslationDomainNormalizer);
  312.         $resolver->setAllowedTypes('choices', ['null''array'\Traversable::class]);
  313.         $resolver->setAllowedTypes('choice_translation_domain', ['null''bool''string']);
  314.         $resolver->setAllowedTypes('choice_loader', ['null'ChoiceLoaderInterface::class, ChoiceLoader::class]);
  315.         $resolver->setAllowedTypes('choice_filter', ['null''callable''string'PropertyPath::class, ChoiceFilter::class]);
  316.         $resolver->setAllowedTypes('choice_label', ['null''bool''callable''string'PropertyPath::class, ChoiceLabel::class]);
  317.         $resolver->setAllowedTypes('choice_name', ['null''callable''string'PropertyPath::class, ChoiceFieldName::class]);
  318.         $resolver->setAllowedTypes('choice_value', ['null''callable''string'PropertyPath::class, ChoiceValue::class]);
  319.         $resolver->setAllowedTypes('choice_attr', ['null''array''callable''string'PropertyPath::class, ChoiceAttr::class]);
  320.         $resolver->setAllowedTypes('choice_translation_parameters', ['null''array''callable'ChoiceTranslationParameters::class]);
  321.         $resolver->setAllowedTypes('preferred_choices', ['array'\Traversable::class, 'callable''string'PropertyPath::class, PreferredChoice::class]);
  322.         $resolver->setAllowedTypes('group_by', ['null''callable''string'PropertyPath::class, GroupBy::class]);
  323.     }
  324.     public function getBlockPrefix(): string
  325.     {
  326.         return 'choice';
  327.     }
  328.     /**
  329.      * Adds the sub fields for an expanded choice field.
  330.      */
  331.     private function addSubForms(FormBuilderInterface $builder, array $choiceViews, array $options)
  332.     {
  333.         foreach ($choiceViews as $name => $choiceView) {
  334.             // Flatten groups
  335.             if (\is_array($choiceView)) {
  336.                 $this->addSubForms($builder$choiceView$options);
  337.                 continue;
  338.             }
  339.             if ($choiceView instanceof ChoiceGroupView) {
  340.                 $this->addSubForms($builder$choiceView->choices$options);
  341.                 continue;
  342.             }
  343.             $this->addSubForm($builder$name$choiceView$options);
  344.         }
  345.     }
  346.     private function addSubForm(FormBuilderInterface $builderstring $nameChoiceView $choiceView, array $options)
  347.     {
  348.         $choiceOpts = [
  349.             'value' => $choiceView->value,
  350.             'label' => $choiceView->label,
  351.             'label_html' => $options['label_html'],
  352.             'attr' => $choiceView->attr,
  353.             'label_translation_parameters' => $choiceView->labelTranslationParameters,
  354.             'translation_domain' => $options['choice_translation_domain'],
  355.             'block_name' => 'entry',
  356.         ];
  357.         if ($options['multiple']) {
  358.             $choiceType CheckboxType::class;
  359.             // The user can check 0 or more checkboxes. If required
  360.             // is true, they are required to check all of them.
  361.             $choiceOpts['required'] = false;
  362.         } else {
  363.             $choiceType RadioType::class;
  364.         }
  365.         $builder->add($name$choiceType$choiceOpts);
  366.     }
  367.     private function createChoiceList(array $options)
  368.     {
  369.         if (null !== $options['choice_loader']) {
  370.             return $this->choiceListFactory->createListFromLoader(
  371.                 $options['choice_loader'],
  372.                 $options['choice_value'],
  373.                 $options['choice_filter']
  374.             );
  375.         }
  376.         // Harden against NULL values (like in EntityType and ModelType)
  377.         $choices null !== $options['choices'] ? $options['choices'] : [];
  378.         return $this->choiceListFactory->createListFromChoices(
  379.             $choices,
  380.             $options['choice_value'],
  381.             $options['choice_filter']
  382.         );
  383.     }
  384.     private function createChoiceListView(ChoiceListInterface $choiceList, array $options)
  385.     {
  386.         return $this->choiceListFactory->createView(
  387.             $choiceList,
  388.             $options['preferred_choices'],
  389.             $options['choice_label'],
  390.             $options['choice_name'],
  391.             $options['group_by'],
  392.             $options['choice_attr'],
  393.             $options['choice_translation_parameters']
  394.         );
  395.     }
  396. }