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

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