vendor/symfony/form/Extension/Core/Type/CheckboxType.php line 21

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\Extension\Core\DataTransformer\BooleanToStringTransformer;
  13. use Symfony\Component\Form\FormBuilderInterface;
  14. use Symfony\Component\Form\FormInterface;
  15. use Symfony\Component\Form\FormView;
  16. use Symfony\Component\OptionsResolver\OptionsResolver;
  17. class CheckboxType extends AbstractType
  18. {
  19.     /**
  20.      * {@inheritdoc}
  21.      */
  22.     public function buildForm(FormBuilderInterface $builder, array $options)
  23.     {
  24.         // Unlike in other types, where the data is NULL by default, it
  25.         // needs to be a Boolean here. setData(null) is not acceptable
  26.         // for checkboxes and radio buttons (unless a custom model
  27.         // transformer handles this case).
  28.         // We cannot solve this case via overriding the "data" option, because
  29.         // doing so also calls setDataLocked(true).
  30.         $builder->setData($options['data'] ?? false);
  31.         $builder->addViewTransformer(new BooleanToStringTransformer($options['value'], $options['false_values']));
  32.         $builder->setAttribute('_false_is_empty'true); // @internal - A boolean flag to treat false as empty, see Form::isEmpty() - Do not rely on it, it will be removed in Symfony 5.1.
  33.     }
  34.     /**
  35.      * {@inheritdoc}
  36.      */
  37.     public function buildView(FormView $viewFormInterface $form, array $options)
  38.     {
  39.         $view->vars array_replace($view->vars, [
  40.             'value' => $options['value'],
  41.             'checked' => null !== $form->getViewData(),
  42.         ]);
  43.     }
  44.     /**
  45.      * {@inheritdoc}
  46.      */
  47.     public function configureOptions(OptionsResolver $resolver)
  48.     {
  49.         $emptyData = function (FormInterface $form$viewData) {
  50.             return $viewData;
  51.         };
  52.         $resolver->setDefaults([
  53.             'value' => '1',
  54.             'empty_data' => $emptyData,
  55.             'compound' => false,
  56.             'false_values' => [null],
  57.         ]);
  58.         $resolver->setAllowedTypes('false_values''array');
  59.     }
  60.     /**
  61.      * {@inheritdoc}
  62.      */
  63.     public function getBlockPrefix()
  64.     {
  65.         return 'checkbox';
  66.     }
  67. }