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

  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.     public function buildForm(FormBuilderInterface $builder, array $options)
  20.     {
  21.         // Unlike in other types, where the data is NULL by default, it
  22.         // needs to be a Boolean here. setData(null) is not acceptable
  23.         // for checkboxes and radio buttons (unless a custom model
  24.         // transformer handles this case).
  25.         // We cannot solve this case via overriding the "data" option, because
  26.         // doing so also calls setDataLocked(true).
  27.         $builder->setData($options['data'] ?? false);
  28.         $builder->addViewTransformer(new BooleanToStringTransformer($options['value'], $options['false_values']));
  29.     }
  30.     public function buildView(FormView $viewFormInterface $form, array $options)
  31.     {
  32.         $view->vars array_replace($view->vars, [
  33.             'value' => $options['value'],
  34.             'checked' => null !== $form->getViewData(),
  35.         ]);
  36.     }
  37.     public function configureOptions(OptionsResolver $resolver)
  38.     {
  39.         $emptyData = function (FormInterface $form$viewData) {
  40.             return $viewData;
  41.         };
  42.         $resolver->setDefaults([
  43.             'value' => '1',
  44.             'empty_data' => $emptyData,
  45.             'compound' => false,
  46.             'false_values' => [null],
  47.             'invalid_message' => 'The checkbox has an invalid value.',
  48.             'is_empty_callback' => static function ($modelData): bool {
  49.                 return false === $modelData;
  50.             },
  51.         ]);
  52.         $resolver->setAllowedTypes('false_values''array');
  53.     }
  54.     public function getBlockPrefix(): string
  55.     {
  56.         return 'checkbox';
  57.     }
  58. }