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