BooleanToStringTransformer example


    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Unlike in other types, where the data is NULL by default, it         // needs to be a Boolean here. setData(null) is not acceptable         // for checkboxes and radio buttons (unless a custom model         // transformer handles this case).         // We cannot solve this case via overriding the "data" option, because         // doing so also calls setDataLocked(true).         $builder->setData($options['data'] ?? false);
        $builder->addViewTransformer(new BooleanToStringTransformer($options['value']$options['false_values']));
    }

    /** * @return void */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars = array_replace($view->vars, [
            'value' => $options['value'],
            'checked' => null !== $form->getViewData(),
        ]);
    }
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Extension\Core\DataTransformer\BooleanToStringTransformer;

class BooleanToStringTransformerTest extends TestCase
{
    private const TRUE_VALUE = '1';

    protected BooleanToStringTransformer $transformer;

    protected function setUp(): void
    {
        $this->transformer = new BooleanToStringTransformer(self::TRUE_VALUE);
    }

    public function testTransform()
    {
        $this->assertEquals(self::TRUE_VALUE, $this->transformer->transform(true));
        $this->assertNull($this->transformer->transform(false));
    }

    // https://github.com/symfony/symfony/issues/8989     public function testTransformAcceptsNull()
    {
        
Home | Imprint | This part of the site doesn't use cookies.