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

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(isset($options['data']) ? $options['data'] : false);
  31.         $builder->addViewTransformer(new BooleanToStringTransformer($options['value'], $options['false_values']));
  32.     }
  33.     /**
  34.      * {@inheritdoc}
  35.      */
  36.     public function buildView(FormView $viewFormInterface $form, array $options)
  37.     {
  38.         $view->vars array_replace($view->vars, [
  39.             'value' => $options['value'],
  40.             'checked' => null !== $form->getViewData(),
  41.         ]);
  42.     }
  43.     /**
  44.      * {@inheritdoc}
  45.      */
  46.     public function configureOptions(OptionsResolver $resolver)
  47.     {
  48.         $emptyData = function (FormInterface $form$viewData) {
  49.             return $viewData;
  50.         };
  51.         $resolver->setDefaults([
  52.             'value' => '1',
  53.             'empty_data' => $emptyData,
  54.             'compound' => false,
  55.             'false_values' => [null],
  56.         ]);
  57.         $resolver->setAllowedTypes('false_values''array');
  58.     }
  59.     /**
  60.      * {@inheritdoc}
  61.      */
  62.     public function getBlockPrefix()
  63.     {
  64.         return 'checkbox';
  65.     }
  66. }