Last active
March 18, 2021 20:50
-
-
Save nebkam/716ebdf89d0259cb1aac411ca7d4349f to your computer and use it in GitHub Desktop.
NullableBooleanType for Symfony REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Form\Type; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\Extension\Core\Type\ChoiceType; | |
use Symfony\Component\Form\CallbackTransformer; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\OptionsResolver\OptionsResolver; | |
class NullableBooleanType extends AbstractType | |
{ | |
public function configureOptions(OptionsResolver $resolver): void | |
{ | |
$resolver->setDefaults([ | |
'required' => false, | |
'choices' => [-1,0,1] | |
]); | |
} | |
public function buildForm(FormBuilderInterface $builder, array $options): void | |
{ | |
$builder | |
->addModelTransformer(new CallbackTransformer( | |
static function($orig) { | |
if ($orig === null) { | |
return 0; | |
} | |
return $orig ? 1 : -1; | |
}, | |
static function($submitted) { | |
if ($submitted === null || $submitted === 0) { | |
return null; | |
} | |
return $submitted === 1; | |
} | |
)); | |
} | |
public function getParent(): string | |
{ | |
return ChoiceType::class; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment