addModelTransformer example

public function testDataIsInitializedToConfiguredValue()
    {
        $model = new FixedDataTransformer([
            'default' => 'foo',
        ]);
        $view = new FixedDataTransformer([
            'foo' => 'bar',
        ]);

        $config = new FormConfigBuilder('name', null, new EventDispatcher());
        $config->addViewTransformer($view);
        $config->addModelTransformer($model);
        $config->setData('default');
        $form = new Form($config);

        $this->assertSame('default', $form->getData());
        $this->assertSame('foo', $form->getNormData());
        $this->assertSame('bar', $form->getViewData());
    }

    public function testDataTransformationFailure()
    {
        $this->expectException(TransformationFailedException::class);
        
'translation_domain' => $options['translation_domain'],
                        // when compound the array entries are ignored, we need to cascade the configuration here                         'empty_data' => $options['empty_data'][$part] ?? null,
                    ];
                    if ('choice' === $options['widget']) {
                        $childOptions['choice_translation_domain'] = false;
                        $childOptions['choices'] = $options[$part];
                        $childOptions['placeholder'] = $options['placeholder'][$part];
                    }
                    $childForm = $builder->create($part, self::WIDGETS[$options['widget']]$childOptions);
                    if ('integer' === $options['widget']) {
                        $childForm->addModelTransformer(
                            new ReversedTransformer(
                                new IntegerToLocalizedStringTransformer()
                            )
                        );
                    }
                    $builder->add($childForm);
                }
            }
            if ($options['with_invert']) {
                $builder->add('invert', CheckboxType::class[
                    'label' => $options['labels']['invert'],
                    

    public function testCustomModelTransformer($data$checked)
    {
        // present a binary status field as a checkbox         $transformer = new CallbackTransformer(
            fn ($value) => 'checked' == $value,
            fn ($value) => $value ? 'checked' : 'unchecked'
        );

        $form = $this->factory->createBuilder(static::TESTED_TYPE)
            ->addModelTransformer($transformer)
            ->getForm();

        $form->setData($data);
        $view = $form->createView();

        $this->assertSame($data$form->getData());
        $this->assertSame($checked$form->getNormData());
        $this->assertEquals($checked$view->vars['checked']);
    }

    public static function provideCustomModelTransformerData()
    {
$this->assertSame([
            'default_data' => [
                'norm' => 'Foobar',
            ],
            'submitted_data' => [],
        ]$this->dataExtractor->extractDefaultData($form));
    }

    public function testExtractDefaultDataStoresModelDataIfDifferent()
    {
        $form = $this->createBuilder('name')
            ->addModelTransformer(new FixedDataTransformer([
                'Foo' => 'Bar',
            ]))
            ->getForm();

        $form->setData('Foo');

        $this->assertSame([
            'default_data' => [
                'norm' => 'Bar',
                'model' => 'Foo',
            ],
            


        $builder->add('additionalAddressLine1', TextType::class[
            'constraints' => $this->getAdditionalAddressline1Constraints(),
        ]);

        $builder->add('additionalAddressLine2', TextType::class[
            'constraints' => $this->getAdditionalAddressline2Constraints(),
        ]);

        // convert IDs to entities         $builder->get('country')->addModelTransformer(new EntityTransformer($this->models, Country::class));
        $builder->get('state')->addModelTransformer(new EntityTransformer($this->models, State::class));

        $builder->add('attribute', AttributeFormType::class[
            'data_class' => AddressAttribute::class,
        ]);

        // dynamic field which contains multiple values         // used for extendable data which has not to persist over attributes         $builder->add('additional', null, [
            'compound' => true,
            'allow_extra_fields' => true,
        ]);
->add('year', self::WIDGETS[$options['widget']]$yearOptions)
                ->add('month', self::WIDGETS[$options['widget']]$monthOptions)
                ->add('day', self::WIDGETS[$options['widget']]$dayOptions)
                ->addViewTransformer(new DateTimeToArrayTransformer(
                    $options['model_timezone']$options['view_timezone']['year', 'month', 'day']
                ))
                ->setAttribute('formatter', $formatter)
            ;
        }

        if ('datetime_immutable' === $options['input']) {
            $builder->addModelTransformer(new DateTimeImmutableToDateTimeTransformer());
        } elseif ('string' === $options['input']) {
            $builder->addModelTransformer(new ReversedTransformer(
                new DateTimeToStringTransformer($options['model_timezone']$options['model_timezone']$options['input_format'])
            ));
        } elseif ('timestamp' === $options['input']) {
            $builder->addModelTransformer(new ReversedTransformer(
                new DateTimeToTimestampTransformer($options['model_timezone']$options['model_timezone'])
            ));
        } elseif ('array' === $options['input']) {
            $builder->addModelTransformer(new ReversedTransformer(
                new DateTimeToArrayTransformer($options['model_timezone']$options['model_timezone']['year', 'month', 'day'])
            ));

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addViewTransformer(new NumberToLocalizedStringTransformer(
            $options['scale'],
            $options['grouping'],
            $options['rounding_mode'],
            $options['html5'] ? 'en' : null
        ));

        if ('string' === $options['input']) {
            $builder->addModelTransformer(new StringToFloatTransformer($options['scale']));
        }
    }

    /** * @return void */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        if ($options['html5']) {
            $view->vars['type'] = 'number';

            
new ArrayToPartsTransformer([
                        'date' => $dateParts,
                        'time' => $timeParts,
                    ]),
                ]))
                ->add('date', DateType::class$dateOptions)
                ->add('time', TimeType::class$timeOptions)
            ;
        }

        if ('datetime_immutable' === $options['input']) {
            $builder->addModelTransformer(new DateTimeImmutableToDateTimeTransformer());
        } elseif ('string' === $options['input']) {
            $builder->addModelTransformer(new ReversedTransformer(
                new DateTimeToStringTransformer($options['model_timezone']$options['model_timezone']$options['input_format'])
            ));
        } elseif ('timestamp' === $options['input']) {
            $builder->addModelTransformer(new ReversedTransformer(
                new DateTimeToTimestampTransformer($options['model_timezone']$options['model_timezone'])
            ));
        } elseif ('array' === $options['input']) {
            $builder->addModelTransformer(new ReversedTransformer(
                new DateTimeToArrayTransformer($options['model_timezone']$options['model_timezone']$parts)
            ));
'compound' => false,
        ]);

        $form->setData('foobar');

        $this->assertNull($form->getData());
    }

    public function testNormDataIsPassedToView()
    {
        $view = $this->factory->createBuilder(static::TESTED_TYPE)
            ->addModelTransformer(new FixedDataTransformer([
                'foo' => 'bar',
            ]))
            ->addViewTransformer(new FixedDataTransformer([
                'bar' => 'baz',
            ]))
            ->setData('foo')
            ->getForm()
            ->createView();

        $this->assertSame('bar', $view->vars['data']);
        $this->assertSame('baz', $view->vars['value']);
    }
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

class TimezoneType extends AbstractType
{
    /** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if ('datetimezone' === $options['input']) {
            $builder->addModelTransformer(new DateTimeZoneToStringTransformer($options['multiple']));
        } elseif ('intltimezone' === $options['input']) {
            $builder->addModelTransformer(new IntlTimeZoneToStringTransformer($options['multiple']));
        }
    }

    /** * @return void */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            
$secondOptions['empty_data'] = $lazyEmptyData('second');
                } elseif (isset($emptyData['second'])) {
                    $secondOptions['empty_data'] = $emptyData['second'];
                }
                $builder->add('second', self::WIDGETS[$options['widget']]$secondOptions);
            }

            $builder->addViewTransformer(new DateTimeToArrayTransformer($options['model_timezone']$options['view_timezone']$parts, 'text' === $options['widget']$options['reference_date']));
        }

        if ('datetime_immutable' === $options['input']) {
            $builder->addModelTransformer(new DateTimeImmutableToDateTimeTransformer());
        } elseif ('string' === $options['input']) {
            $builder->addModelTransformer(new ReversedTransformer(
                new DateTimeToStringTransformer($options['model_timezone']$options['model_timezone']$options['input_format'])
            ));
        } elseif ('timestamp' === $options['input']) {
            $builder->addModelTransformer(new ReversedTransformer(
                new DateTimeToTimestampTransformer($options['model_timezone']$options['model_timezone'])
            ));
        } elseif ('array' === $options['input']) {
            $builder->addModelTransformer(new ReversedTransformer(
                new DateTimeToArrayTransformer($options['model_timezone']$options['model_timezone']$parts, 'text' === $options['widget']$options['reference_date'])
            ));
$this->assertSame('Please enter a valid date.', $form->getErrors()[0]->getMessage());
        $this->assertSame($form->get('year')$form->getErrors()[0]->getOrigin());
        $this->assertSame('Please enter a valid date.', $form->getErrors()[1]->getMessage());
        $this->assertSame($form->get('month')$form->getErrors()[1]->getOrigin());
    }

    public function testDoNotAddInvalidMessageIfChildFormIsAlreadyNotSynchronized()
    {
        $formBuilder = $this->formFactory->createBuilder()
            ->add('field1')
            ->add('field2')
            ->addModelTransformer(new CallbackTransformer(
                function D) {
                },
                function D) {
                    throw new TransformationFailedException('This value is invalid.');
                }
            ));
        $formBuilder->get('field2')->addModelTransformer(new CallbackTransformer(
            function D) {
            },
            function D) {
                throw new TransformationFailedException('This value is invalid.');
            }
private const WIDGETS = [
        'text' => IntegerType::class,
        'choice' => ChoiceType::class,
    ];

    /** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if ('string' === $options['input']) {
            $builder->addModelTransformer(new WeekToArrayTransformer());
        }

        if ('single_text' === $options['widget']) {
            $builder->addViewTransformer(new ReversedTransformer(new WeekToArrayTransformer()));
        } else {
            $yearOptions = $weekOptions = [
                'error_bubbling' => true,
                'empty_data' => '',
            ];
            // when the form is compound the entries of the array are ignored in favor of children data             // so we need to handle the cascade setting here
Home | Imprint | This part of the site doesn't use cookies.