Created
June 16, 2015 20:25
-
-
Save Maff-/a040d5fc41e3f675cd27 to your computer and use it in GitHub Desktop.
Symfony: Boolean as [No, Yes] radio Choice list
This file contains hidden or 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 AppBundle\Form\Type; | |
use AppBundle\Form\DataTransformer\BoolToIntTransformer; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\OptionsResolver\OptionsResolver; | |
class BoolChoiceType extends AbstractType | |
{ | |
/** | |
* @inheritdoc | |
*/ | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
$nullable = $options['placeholder'] !== null; | |
$builder->addModelTransformer(new BoolToIntTransformer($nullable)); | |
} | |
/** | |
* @inheritdoc | |
*/ | |
public function configureOptions(OptionsResolver $resolver) | |
{ | |
$resolver->setDefaults([ | |
'expanded' => true, | |
'no_label' => 'No', | |
'yes_label' => 'Yes', | |
]); | |
$resolver->setNormalizer('choices', function ($options, $choices) { | |
$choices[0] = $options['no_label']; | |
$choices[1] = $options['yes_label']; | |
return $choices; | |
}); | |
} | |
/** | |
* @inheritdoc | |
*/ | |
public function getParent() | |
{ | |
return 'choice'; | |
} | |
/** | |
* @inheritdoc | |
*/ | |
public function getName() | |
{ | |
return 'bool_choice'; | |
} | |
} |
This file contains hidden or 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 AppBundle\Form\DataTransformer; | |
use Symfony\Component\Form\DataTransformerInterface; | |
use Symfony\Component\Form\Exception\TransformationFailedException; | |
class BoolToIntTransformer implements DataTransformerInterface | |
{ | |
/** | |
* @var bool | |
*/ | |
private $nullable; | |
/** | |
* @var mixed | |
*/ | |
private $nullValue; | |
public function __construct($nullable = true, $nullValue = '') | |
{ | |
$this->nullValue = $nullValue; | |
$this->nullable = $nullable; | |
} | |
/** | |
* @inheritdoc | |
*/ | |
public function transform($value) | |
{ | |
var_dump(['transform' => $value]); | |
if ($this->nullable && $value === null) { | |
return $this->nullValue; | |
} | |
return (int) $value; | |
} | |
/** | |
* @inheritdoc | |
*/ | |
public function reverseTransform($value) | |
{ | |
var_dump(['reverseTransform' => $value]); | |
if ($this->nullable && $value === $this->nullValue) { | |
return null; | |
} | |
return (bool) $value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment