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 ($choiceList->getChoicesForValues($data) as $key => $choice) {
  127.                         $knownValues[] = $data[$key];
  128.                         unset($unknownValues[$data[$key]]);
  129.                     }
  130.                 }
  131.                 // The empty value is always known, independent of whether a
  132.                 // field exists for it or not
  133.                 unset($unknownValues['']);
  134.                 // Throw exception if unknown values were submitted (multiple choices will be handled in a different event listener below)
  135.                 if (\count($unknownValues) > && !$options['multiple']) {
  136.                     throw new TransformationFailedException(sprintf('The choices "%s" do not exist in the choice list.'implode('", "'array_keys($unknownValues))));
  137.                 }
  138.                 $event->setData($knownValues);
  139.             });
  140.         }
  141.         if ($options['multiple']) {
  142.             $messageTemplate $options['invalid_message'] ?? 'The value {{ value }} is not valid.';
  143.             $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use (&$unknownValues$messageTemplate) {
  144.                 // Throw exception if unknown values were submitted
  145.                 if (\count($unknownValues) > 0) {
  146.                     $form $event->getForm();
  147.                     $clientDataAsString \is_scalar($form->getViewData()) ? (string) $form->getViewData() : (\is_array($form->getViewData()) ? implode('", "'array_keys($unknownValues)) : \gettype($form->getViewData()));
  148.                     if (null !== $this->translator) {
  149.                         $message $this->translator->trans($messageTemplate, ['{{ value }}' => $clientDataAsString], 'validators');
  150.                     } else {
  151.                         $message strtr($messageTemplate, ['{{ value }}' => $clientDataAsString]);
  152.                     }
  153.                     $form->addError(new FormError($message$messageTemplate, ['{{ value }}' => $clientDataAsString], null, new TransformationFailedException(sprintf('The choices "%s" do not exist in the choice list.'$clientDataAsString))));
  154.                 }
  155.             });
  156.             // <select> tag with "multiple" option or list of checkbox inputs
  157.             $builder->addViewTransformer(new ChoicesToValuesTransformer($choiceList));
  158.         } else {
  159.             // <select> tag without "multiple" option or list of radio inputs
  160.             $builder->addViewTransformer(new ChoiceToValueTransformer($choiceList));
  161.         }
  162.         if ($options['multiple'] && $options['by_reference']) {
  163.             // Make sure the collection created during the client->norm
  164.             // transformation is merged back into the original collection
  165.             $builder->addEventSubscriber(new MergeCollectionListener(truetrue));
  166.         }
  167.         // To avoid issues when the submitted choices are arrays (i.e. array to string conversions),
  168.         // we have to ensure that all elements of the submitted choice data are NULL, strings or ints.
  169.         $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
  170.             $data $event->getData();
  171.             if (!\is_array($data)) {
  172.                 return;
  173.             }
  174.             foreach ($data as $v) {
  175.                 if (null !== $v && !\is_string($v) && !\is_int($v)) {
  176.                     throw new TransformationFailedException('All choices submitted must be NULL, strings or ints.');
  177.                 }
  178.             }
  179.         }, 256);
  180.     }
  181.     public function buildView(FormView $viewFormInterface $form, array $options)
  182.     {
  183.         $choiceTranslationDomain $options['choice_translation_domain'];
  184.         if ($view->parent && null === $choiceTranslationDomain) {
  185.             $choiceTranslationDomain $view->vars['translation_domain'];
  186.         }
  187.         /** @var ChoiceListInterface $choiceList */
  188.         $choiceList $form->getConfig()->getAttribute('choice_list');
  189.         /** @var ChoiceListView $choiceListView */
  190.         $choiceListView $form->getConfig()->hasAttribute('choice_list_view')
  191.             ? $form->getConfig()->getAttribute('choice_list_view')
  192.             : $this->createChoiceListView($choiceList$options);
  193.         $view->vars array_replace($view->vars, [
  194.             'multiple' => $options['multiple'],
  195.             'expanded' => $options['expanded'],
  196.             'preferred_choices' => $choiceListView->preferredChoices,
  197.             'choices' => $choiceListView->choices,
  198.             'separator' => '-------------------',
  199.             'placeholder' => null,
  200.             'choice_translation_domain' => $choiceTranslationDomain,
  201.             'choice_translation_parameters' => $options['choice_translation_parameters'],
  202.         ]);
  203.         // The decision, whether a choice is selected, is potentially done
  204.         // thousand of times during the rendering of a template. Provide a
  205.         // closure here that is optimized for the value of the form, to
  206.         // avoid making the type check inside the closure.
  207.         if ($options['multiple']) {
  208.             $view->vars['is_selected'] = function ($choice, array $values) {
  209.                 return \in_array($choice$valuestrue);
  210.             };
  211.         } else {
  212.             $view->vars['is_selected'] = function ($choice$value) {
  213.                 return $choice === $value;
  214.             };
  215.         }
  216.         // Check if the choices already contain the empty value
  217.         $view->vars['placeholder_in_choices'] = $choiceListView->hasPlaceholder();
  218.         // Only add the empty value option if this is not the case
  219.         if (null !== $options['placeholder'] && !$view->vars['placeholder_in_choices']) {
  220.             $view->vars['placeholder'] = $options['placeholder'];
  221.         }
  222.         if ($options['multiple'] && !$options['expanded']) {
  223.             // Add "[]" to the name in case a select tag with multiple options is
  224.             // displayed. Otherwise only one of the selected options is sent in the
  225.             // POST request.
  226.             $view->vars['full_name'] .= '[]';
  227.         }
  228.     }
  229.     public function finishView(FormView $viewFormInterface $form, array $options)
  230.     {
  231.         if ($options['expanded']) {
  232.             // Radio buttons should have the same name as the parent
  233.             $childName $view->vars['full_name'];
  234.             // Checkboxes should append "[]" to allow multiple selection
  235.             if ($options['multiple']) {
  236.                 $childName .= '[]';
  237.             }
  238.             foreach ($view as $childView) {
  239.                 $childView->vars['full_name'] = $childName;
  240.             }
  241.         }
  242.     }
  243.     public function configureOptions(OptionsResolver $resolver)
  244.     {
  245.         $emptyData = function (Options $options) {
  246.             if ($options['expanded'] && !$options['multiple']) {
  247.                 return null;
  248.             }
  249.             if ($options['multiple']) {
  250.                 return [];
  251.             }
  252.             return '';
  253.         };
  254.         $placeholderDefault = function (Options $options) {
  255.             return $options['required'] ? null '';
  256.         };
  257.         $placeholderNormalizer = function (Options $options$placeholder) {
  258.             if ($options['multiple']) {
  259.                 // never use an empty value for this case
  260.                 return null;
  261.             } elseif ($options['required'] && ($options['expanded'] || isset($options['attr']['size']) && $options['attr']['size'] > 1)) {
  262.                 // placeholder for required radio buttons or a select with size > 1 does not make sense
  263.                 return null;
  264.             } elseif (false === $placeholder) {
  265.                 // an empty value should be added but the user decided otherwise
  266.                 return null;
  267.             } elseif ($options['expanded'] && '' === $placeholder) {
  268.                 // never use an empty label for radio buttons
  269.                 return 'None';
  270.             }
  271.             // empty value has been set explicitly
  272.             return $placeholder;
  273.         };
  274.         $compound = function (Options $options) {
  275.             return $options['expanded'];
  276.         };
  277.         $choiceTranslationDomainNormalizer = function (Options $options$choiceTranslationDomain) {
  278.             if (true === $choiceTranslationDomain) {
  279.                 return $options['translation_domain'];
  280.             }
  281.             return $choiceTranslationDomain;
  282.         };
  283.         $resolver->setDefaults([
  284.             'multiple' => false,
  285.             'expanded' => false,
  286.             'choices' => [],
  287.             'choice_filter' => null,
  288.             'choice_loader' => null,
  289.             'choice_label' => null,
  290.             'choice_name' => null,
  291.             'choice_value' => null,
  292.             'choice_attr' => null,
  293.             'choice_translation_parameters' => [],
  294.             'preferred_choices' => [],
  295.             'group_by' => null,
  296.             'empty_data' => $emptyData,
  297.             'placeholder' => $placeholderDefault,
  298.             'error_bubbling' => false,
  299.             'compound' => $compound,
  300.             // The view data is always a string or an array of strings,
  301.             // even if the "data" option is manually set to an object.
  302.             // See https://github.com/symfony/symfony/pull/5582
  303.             'data_class' => null,
  304.             'choice_translation_domain' => true,
  305.             'trim' => false,
  306.             'invalid_message' => 'The selected choice is invalid.',
  307.         ]);
  308.         $resolver->setNormalizer('placeholder'$placeholderNormalizer);
  309.         $resolver->setNormalizer('choice_translation_domain'$choiceTranslationDomainNormalizer);
  310.         $resolver->setAllowedTypes('choices', ['null''array'\Traversable::class]);
  311.         $resolver->setAllowedTypes('choice_translation_domain', ['null''bool''string']);
  312.         $resolver->setAllowedTypes('choice_loader', ['null'ChoiceLoaderInterface::class, ChoiceLoader::class]);
  313.         $resolver->setAllowedTypes('choice_filter', ['null''callable''string'PropertyPath::class, ChoiceFilter::class]);
  314.         $resolver->setAllowedTypes('choice_label', ['null''bool''callable''string'PropertyPath::class, ChoiceLabel::class]);
  315.         $resolver->setAllowedTypes('choice_name', ['null''callable''string'PropertyPath::class, ChoiceFieldName::class]);
  316.         $resolver->setAllowedTypes('choice_value', ['null''callable''string'PropertyPath::class, ChoiceValue::class]);
  317.         $resolver->setAllowedTypes('choice_attr', ['null''array''callable''string'PropertyPath::class, ChoiceAttr::class]);
  318.         $resolver->setAllowedTypes('choice_translation_parameters', ['null''array''callable'ChoiceTranslationParameters::class]);
  319.         $resolver->setAllowedTypes('preferred_choices', ['array'\Traversable::class, 'callable''string'PropertyPath::class, PreferredChoice::class]);
  320.         $resolver->setAllowedTypes('group_by', ['null''callable''string'PropertyPath::class, GroupBy::class]);
  321.     }
  322.     public function getBlockPrefix(): string
  323.     {
  324.         return 'choice';
  325.     }
  326.     /**
  327.      * Adds the sub fields for an expanded choice field.
  328.      */
  329.     private function addSubForms(FormBuilderInterface $builder, array $choiceViews, array $options)
  330.     {
  331.         foreach ($choiceViews as $name => $choiceView) {
  332.             // Flatten groups
  333.             if (\is_array($choiceView)) {
  334.                 $this->addSubForms($builder$choiceView$options);
  335.                 continue;
  336.             }
  337.             if ($choiceView instanceof ChoiceGroupView) {
  338.                 $this->addSubForms($builder$choiceView->choices$options);
  339.                 continue;
  340.             }
  341.             $this->addSubForm($builder$name$choiceView$options);
  342.         }
  343.     }
  344.     private function addSubForm(FormBuilderInterface $builderstring $nameChoiceView $choiceView, array $options)
  345.     {
  346.         $choiceOpts = [
  347.             'value' => $choiceView->value,
  348.             'label' => $choiceView->label,
  349.             'label_html' => $options['label_html'],
  350.             'attr' => $choiceView->attr,
  351.             'label_translation_parameters' => $choiceView->labelTranslationParameters,
  352.             'translation_domain' => $options['choice_translation_domain'],
  353.             'block_name' => 'entry',
  354.         ];
  355.         if ($options['multiple']) {
  356.             $choiceType CheckboxType::class;
  357.             // The user can check 0 or more checkboxes. If required
  358.             // is true, they are required to check all of them.
  359.             $choiceOpts['required'] = false;
  360.         } else {
  361.             $choiceType RadioType::class;
  362.         }
  363.         $builder->add($name$choiceType$choiceOpts);
  364.     }
  365.     private function createChoiceList(array $options)
  366.     {
  367.         if (null !== $options['choice_loader']) {
  368.             return $this->choiceListFactory->createListFromLoader(
  369.                 $options['choice_loader'],
  370.                 $options['choice_value'],
  371.                 $options['choice_filter']
  372.             );
  373.         }
  374.         // Harden against NULL values (like in EntityType and ModelType)
  375.         $choices null !== $options['choices'] ? $options['choices'] : [];
  376.         return $this->choiceListFactory->createListFromChoices(
  377.             $choices,
  378.             $options['choice_value'],
  379.             $options['choice_filter']
  380.         );
  381.     }
  382.     private function createChoiceListView(ChoiceListInterface $choiceList, array $options)
  383.     {
  384.         return $this->choiceListFactory->createView(
  385.             $choiceList,
  386.             $options['preferred_choices'],
  387.             $options['choice_label'],
  388.             $options['choice_name'],
  389.             $options['group_by'],
  390.             $options['choice_attr'],
  391.             $options['choice_translation_parameters']
  392.         );
  393.     }
  394. }