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

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