Skip to content

Instantly share code, notes, and snippets.

@nebkam
Last active March 18, 2021 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nebkam/716ebdf89d0259cb1aac411ca7d4349f to your computer and use it in GitHub Desktop.
Save nebkam/716ebdf89d0259cb1aac411ca7d4349f to your computer and use it in GitHub Desktop.
NullableBooleanType for Symfony REST API
<?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