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

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\ChoiceValue;
  19. use Symfony\Component\Form\ChoiceList\Factory\Cache\GroupBy;
  20. use Symfony\Component\Form\ChoiceList\Factory\Cache\PreferredChoice;
  21. use Symfony\Component\Form\ChoiceList\Factory\CachingFactoryDecorator;
  22. use Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface;
  23. use Symfony\Component\Form\ChoiceList\Factory\DefaultChoiceListFactory;
  24. use Symfony\Component\Form\ChoiceList\Factory\PropertyAccessDecorator;
  25. use Symfony\Component\Form\ChoiceList\Loader\ChoiceLoaderInterface;
  26. use Symfony\Component\Form\ChoiceList\View\ChoiceGroupView;
  27. use Symfony\Component\Form\ChoiceList\View\ChoiceListView;
  28. use Symfony\Component\Form\ChoiceList\View\ChoiceView;
  29. use Symfony\Component\Form\Exception\TransformationFailedException;
  30. use Symfony\Component\Form\Extension\Core\DataMapper\CheckboxListMapper;
  31. use Symfony\Component\Form\Extension\Core\DataMapper\RadioListMapper;
  32. use Symfony\Component\Form\Extension\Core\DataTransformer\ChoicesToValuesTransformer;
  33. use Symfony\Component\Form\Extension\Core\DataTransformer\ChoiceToValueTransformer;
  34. use Symfony\Component\Form\Extension\Core\EventListener\MergeCollectionListener;
  35. use Symfony\Component\Form\FormBuilderInterface;
  36. use Symfony\Component\Form\FormError;
  37. use Symfony\Component\Form\FormEvent;
  38. use Symfony\Component\Form\FormEvents;
  39. use Symfony\Component\Form\FormInterface;
  40. use Symfony\Component\Form\FormView;
  41. use Symfony\Component\OptionsResolver\Options;
  42. use Symfony\Component\OptionsResolver\OptionsResolver;
  43. use Symfony\Component\PropertyAccess\PropertyPath;
  44. use Symfony\Contracts\Translation\TranslatorInterface;
  45. class ChoiceType extends AbstractType
  46. {
  47.     private $choiceListFactory;
  48.     private $translator;
  49.     /**
  50.      * @param TranslatorInterface $translator
  51.      */
  52.     public function __construct(ChoiceListFactoryInterface $choiceListFactory null$translator null)
  53.     {
  54.         $this->choiceListFactory $choiceListFactory ?: new CachingFactoryDecorator(
  55.             new PropertyAccessDecorator(
  56.                 new DefaultChoiceListFactory()
  57.             )
  58.         );
  59.         // BC, to be removed in 6.0
  60.         if ($this->choiceListFactory instanceof CachingFactoryDecorator) {
  61.             return;
  62.         }
  63.         $ref = new \ReflectionMethod($this->choiceListFactory'createListFromChoices');
  64.         if ($ref->getNumberOfParameters() < 3) {
  65.             trigger_deprecation('symfony/form''5.1''Not defining a third parameter "callable|null $filter" in "%s::%s()" is deprecated.'$ref->class$ref->name);
  66.         }
  67.         if (null !== $translator && !$translator instanceof TranslatorInterface) {
  68.             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)));
  69.         }
  70.         $this->translator $translator;
  71.     }
  72.     /**
  73.      * {@inheritdoc}
  74.      */
  75.     public function buildForm(FormBuilderInterface $builder, array $options)
  76.     {
  77.         $unknownValues = [];
  78.         $choiceList $this->createChoiceList($options);
  79.         $builder->setAttribute('choice_list'$choiceList);
  80.         if ($options['expanded']) {
  81.             $builder->setDataMapper($options['multiple'] ? new CheckboxListMapper() : new RadioListMapper());
  82.             // Initialize all choices before doing the index check below.
  83.             // This helps in cases where index checks are optimized for non
  84.             // initialized choice lists. For example, when using an SQL driver,
  85.             // the index check would read in one SQL query and the initialization
  86.             // requires another SQL query. When the initialization is done first,
  87.             // one SQL query is sufficient.
  88.             $choiceListView $this->createChoiceListView($choiceList$options);
  89.             $builder->setAttribute('choice_list_view'$choiceListView);
  90.             // Check if the choices already contain the empty value
  91.             // Only add the placeholder option if this is not the case
  92.             if (null !== $options['placeholder'] && === \count($choiceList->getChoicesForValues(['']))) {
  93.                 $placeholderView = new ChoiceView(null''$options['placeholder']);
  94.                 // "placeholder" is a reserved name
  95.                 $this->addSubForm($builder'placeholder'$placeholderView$options);
  96.             }
  97.             $this->addSubForms($builder$choiceListView->preferredChoices$options);
  98.             $this->addSubForms($builder$choiceListView->choices$options);
  99.         }
  100.         if ($options['expanded'] || $options['multiple']) {
  101.             // Make sure that scalar, submitted values are converted to arrays
  102.             // which can be submitted to the checkboxes/radio buttons
  103.             $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($choiceList$options, &$unknownValues) {
  104.                 $form $event->getForm();
  105.                 $data $event->getData();
  106.                 // Since the type always use mapper an empty array will not be
  107.                 // considered as empty in Form::submit(), we need to evaluate
  108.                 // empty data here so its value is submitted to sub forms
  109.                 if (null === $data) {
  110.                     $emptyData $form->getConfig()->getEmptyData();
  111.                     $data $emptyData instanceof \Closure $emptyData($form$data) : $emptyData;
  112.                 }
  113.                 // Convert the submitted data to a string, if scalar, before
  114.                 // casting it to an array
  115.                 if (!\is_array($data)) {
  116.                     if ($options['multiple']) {
  117.                         throw new TransformationFailedException('Expected an array.');
  118.                     }
  119.                     $data = (array) (string) $data;
  120.                 }
  121.                 // A map from submitted values to integers
  122.                 $valueMap array_flip($data);
  123.                 // Make a copy of the value map to determine whether any unknown
  124.                 // values were submitted
  125.                 $unknownValues $valueMap;
  126.                 // Reconstruct the data as mapping from child names to values
  127.                 $knownValues = [];
  128.                 if ($options['expanded']) {
  129.                     /** @var FormInterface $child */
  130.                     foreach ($form as $child) {
  131.                         $value $child->getConfig()->getOption('value');
  132.                         // Add the value to $data with the child's name as key
  133.                         if (isset($valueMap[$value])) {
  134.                             $knownValues[$child->getName()] = $value;
  135.                             unset($unknownValues[$value]);
  136.                             continue;
  137.                         } else {
  138.                             $knownValues[$child->getName()] = null;
  139.                         }
  140.                     }
  141.                 } else {
  142.                     foreach ($data as $value) {
  143.                         if ($choiceList->getChoicesForValues([$value])) {
  144.                             $knownValues[] = $value;
  145.                             unset($unknownValues[$value]);
  146.                         }
  147.                     }
  148.                 }
  149.                 // The empty value is always known, independent of whether a
  150.                 // field exists for it or not
  151.                 unset($unknownValues['']);
  152.                 // Throw exception if unknown values were submitted (multiple choices will be handled in a different event listener below)
  153.                 if (\count($unknownValues) > && !$options['multiple']) {
  154.                     throw new TransformationFailedException(sprintf('The choices "%s" do not exist in the choice list.'implode('", "'array_keys($unknownValues))));
  155.                 }
  156.                 $event->setData($knownValues);
  157.             });
  158.         }
  159.         if ($options['multiple']) {
  160.             $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use (&$unknownValues) {
  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() : \gettype($form->getViewData());
  165.                     $messageTemplate 'The value {{ value }} is not valid.';
  166.                     if (null !== $this->translator) {
  167.                         $message $this->translator->trans($messageTemplate, ['{{ value }}' => $clientDataAsString], 'validators');
  168.                     } else {
  169.                         $message strtr($messageTemplate, ['{{ value }}' => $clientDataAsString]);
  170.                     }
  171.                     $form->addError(new FormError($message$messageTemplate, ['{{ value }}' => $clientDataAsString], null, new TransformationFailedException(sprintf('The choices "%s" do not exist in the choice list.'implode('", "'array_keys($unknownValues))))));
  172.                 }
  173.             });
  174.             // <select> tag with "multiple" option or list of checkbox inputs
  175.             $builder->addViewTransformer(new ChoicesToValuesTransformer($choiceList));
  176.         } else {
  177.             // <select> tag without "multiple" option or list of radio inputs
  178.             $builder->addViewTransformer(new ChoiceToValueTransformer($choiceList));
  179.         }
  180.         if ($options['multiple'] && $options['by_reference']) {
  181.             // Make sure the collection created during the client->norm
  182.             // transformation is merged back into the original collection
  183.             $builder->addEventSubscriber(new MergeCollectionListener(truetrue));
  184.         }
  185.         // To avoid issues when the submitted choices are arrays (i.e. array to string conversions),
  186.         // we have to ensure that all elements of the submitted choice data are NULL, strings or ints.
  187.         $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
  188.             $data $event->getData();
  189.             if (!\is_array($data)) {
  190.                 return;
  191.             }
  192.             foreach ($data as $v) {
  193.                 if (null !== $v && !\is_string($v) && !\is_int($v)) {
  194.                     throw new TransformationFailedException('All choices submitted must be NULL, strings or ints.');
  195.                 }
  196.             }
  197.         }, 256);
  198.     }
  199.     /**
  200.      * {@inheritdoc}
  201.      */
  202.     public function buildView(FormView $viewFormInterface $form, array $options)
  203.     {
  204.         $choiceTranslationDomain $options['choice_translation_domain'];
  205.         if ($view->parent && null === $choiceTranslationDomain) {
  206.             $choiceTranslationDomain $view->vars['translation_domain'];
  207.         }
  208.         /** @var ChoiceListInterface $choiceList */
  209.         $choiceList $form->getConfig()->getAttribute('choice_list');
  210.         /** @var ChoiceListView $choiceListView */
  211.         $choiceListView $form->getConfig()->hasAttribute('choice_list_view')
  212.             ? $form->getConfig()->getAttribute('choice_list_view')
  213.             : $this->createChoiceListView($choiceList$options);
  214.         $view->vars array_replace($view->vars, [
  215.             'multiple' => $options['multiple'],
  216.             'expanded' => $options['expanded'],
  217.             'preferred_choices' => $choiceListView->preferredChoices,
  218.             'choices' => $choiceListView->choices,
  219.             'separator' => '-------------------',
  220.             'placeholder' => null,
  221.             'choice_translation_domain' => $choiceTranslationDomain,
  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.             'preferred_choices' => [],
  320.             'group_by' => null,
  321.             'empty_data' => $emptyData,
  322.             'placeholder' => $placeholderDefault,
  323.             'error_bubbling' => false,
  324.             'compound' => $compound,
  325.             // The view data is always a string or an array of strings,
  326.             // even if the "data" option is manually set to an object.
  327.             // See https://github.com/symfony/symfony/pull/5582
  328.             'data_class' => null,
  329.             'choice_translation_domain' => true,
  330.             'trim' => false,
  331.             'invalid_message' => function (Options $options$previousValue) {
  332.                 return ($options['legacy_error_messages'] ?? true)
  333.                     ? $previousValue
  334.                     'The selected choice is invalid.';
  335.             },
  336.         ]);
  337.         $resolver->setNormalizer('placeholder'$placeholderNormalizer);
  338.         $resolver->setNormalizer('choice_translation_domain'$choiceTranslationDomainNormalizer);
  339.         $resolver->setAllowedTypes('choices', ['null''array', \Traversable::class]);
  340.         $resolver->setAllowedTypes('choice_translation_domain', ['null''bool''string']);
  341.         $resolver->setAllowedTypes('choice_loader', ['null'ChoiceLoaderInterface::class, ChoiceLoader::class]);
  342.         $resolver->setAllowedTypes('choice_filter', ['null''callable''string'PropertyPath::class, ChoiceFilter::class]);
  343.         $resolver->setAllowedTypes('choice_label', ['null''bool''callable''string'PropertyPath::class, ChoiceLabel::class]);
  344.         $resolver->setAllowedTypes('choice_name', ['null''callable''string'PropertyPath::class, ChoiceFieldName::class]);
  345.         $resolver->setAllowedTypes('choice_value', ['null''callable''string'PropertyPath::class, ChoiceValue::class]);
  346.         $resolver->setAllowedTypes('choice_attr', ['null''array''callable''string'PropertyPath::class, ChoiceAttr::class]);
  347.         $resolver->setAllowedTypes('preferred_choices', ['array', \Traversable::class, 'callable''string'PropertyPath::class, PreferredChoice::class]);
  348.         $resolver->setAllowedTypes('group_by', ['null''callable''string'PropertyPath::class, GroupBy::class]);
  349.     }
  350.     /**
  351.      * {@inheritdoc}
  352.      */
  353.     public function getBlockPrefix()
  354.     {
  355.         return 'choice';
  356.     }
  357.     /**
  358.      * Adds the sub fields for an expanded choice field.
  359.      */
  360.     private function addSubForms(FormBuilderInterface $builder, array $choiceViews, array $options)
  361.     {
  362.         foreach ($choiceViews as $name => $choiceView) {
  363.             // Flatten groups
  364.             if (\is_array($choiceView)) {
  365.                 $this->addSubForms($builder$choiceView$options);
  366.                 continue;
  367.             }
  368.             if ($choiceView instanceof ChoiceGroupView) {
  369.                 $this->addSubForms($builder$choiceView->choices$options);
  370.                 continue;
  371.             }
  372.             $this->addSubForm($builder$name$choiceView$options);
  373.         }
  374.     }
  375.     private function addSubForm(FormBuilderInterface $builderstring $nameChoiceView $choiceView, array $options)
  376.     {
  377.         $choiceOpts = [
  378.             'value' => $choiceView->value,
  379.             'label' => $choiceView->label,
  380.             'label_html' => $options['label_html'],
  381.             'attr' => $choiceView->attr,
  382.             'translation_domain' => $options['choice_translation_domain'],
  383.             'block_name' => 'entry',
  384.         ];
  385.         if ($options['multiple']) {
  386.             $choiceType CheckboxType::class;
  387.             // The user can check 0 or more checkboxes. If required
  388.             // is true, they are required to check all of them.
  389.             $choiceOpts['required'] = false;
  390.         } else {
  391.             $choiceType RadioType::class;
  392.         }
  393.         $builder->add($name$choiceType$choiceOpts);
  394.     }
  395.     private function createChoiceList(array $options)
  396.     {
  397.         if (null !== $options['choice_loader']) {
  398.             return $this->choiceListFactory->createListFromLoader(
  399.                 $options['choice_loader'],
  400.                 $options['choice_value'],
  401.                 $options['choice_filter']
  402.             );
  403.         }
  404.         // Harden against NULL values (like in EntityType and ModelType)
  405.         $choices null !== $options['choices'] ? $options['choices'] : [];
  406.         return $this->choiceListFactory->createListFromChoices(
  407.             $choices,
  408.             $options['choice_value'],
  409.             $options['choice_filter']
  410.         );
  411.     }
  412.     private function createChoiceListView(ChoiceListInterface $choiceList, array $options)
  413.     {
  414.         return $this->choiceListFactory->createView(
  415.             $choiceList,
  416.             $options['preferred_choices'],
  417.             $options['choice_label'],
  418.             $options['choice_name'],
  419.             $options['group_by'],
  420.             $options['choice_attr']
  421.         );
  422.     }
  423. }