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

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