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

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