addViewTransformer example

if ($translator) {
                        $message = $translator->trans($messageTemplate['{{ value }}' => $clientDataAsString], 'validators');
                    } else {
                        $message = strtr($messageTemplate['{{ value }}' => $clientDataAsString]);
                    }

                    $form->addError(new FormError($message$messageTemplate['{{ value }}' => $clientDataAsString], null, new TransformationFailedException(sprintf('The choices "%s" do not exist in the choice list.', $clientDataAsString))));
                }
            });

            // <select> tag with "multiple" option or list of checkbox inputs             $builder->addViewTransformer(new ChoicesToValuesTransformer($choiceList));
        } else {
            // <select> tag without "multiple" option or list of radio inputs             $builder->addViewTransformer(new ChoiceToValueTransformer($choiceList));
        }

        if ($options['multiple'] && $options['by_reference']) {
            // Make sure the collection created during the client->norm             // transformation is merged back into the original collection             $builder->addEventSubscriber(new MergeCollectionListener(true, true));
        }

        
/** * @author Pavel Dyakonov <wapinet@mail.ru> */
class UlidType extends AbstractType
{
    /** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->addViewTransformer(new UlidToStringTransformer())
        ;
    }

    /** * @return void */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'compound' => false,
            'invalid_message' => 'Please enter a valid ULID.',
        ]);
/** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // When empty_data is explicitly set to an empty string,         // a string should always be returned when NULL is submitted         // This gives more control and thus helps preventing some issues         // with PHP 7 which allows type hinting strings in functions         // See https://github.com/symfony/symfony/issues/5906#issuecomment-203189375         if ('' === $options['empty_data']) {
            $builder->addViewTransformer($this);
        }
    }

    /** * @return void */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'compound' => false,
        ]);
    }

    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(),
        ]);
    }
public function testSetDataDoesNotMapViewDataToChildrenWithLockedSetData()
    {
        $mapper = new DataMapper();
        $viewData = [
            'firstName' => 'Fabien',
            'lastName' => 'Pot',
        ];
        $form = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($mapper)
            ->addViewTransformer(new FixedDataTransformer([
                '' => '',
                'foo' => $viewData,
            ]))
            ->getForm();

        $form->add($child1 = $this->getBuilder('firstName')->getForm());
        $form->add($child2 = $this->getBuilder('lastName')->setData('Potencier')->setDataLocked(true)->getForm());

        $form->setData('foo');

        $this->assertSame('Fabien', $form->get('firstName')->getData());
        
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()
    {
        
$pattern = \is_string($options['format']) ? $options['format'] : '';

        if (!\in_array($dateFormat, self::ACCEPTED_FORMATS, true)) {
            throw new InvalidOptionsException('The "format" option must be one of the IntlDateFormatter constants (FULL, LONG, MEDIUM, SHORT) or a string representing a custom format.');
        }

        if ('single_text' === $options['widget']) {
            if ('' !== $pattern && !str_contains($pattern, 'y') && !str_contains($pattern, 'M') && !str_contains($pattern, 'd')) {
                throw new InvalidOptionsException(sprintf('The "format" option should contain the letters "y", "M" or "d". Its current value is "%s".', $pattern));
            }

            $builder->addViewTransformer(new DateTimeToLocalizedStringTransformer(
                $options['model_timezone'],
                $options['view_timezone'],
                $dateFormat,
                $timeFormat,
                $calendar,
                $pattern
            ));
        } else {
            if ('' !== $pattern && (!str_contains($pattern, 'y') || !str_contains($pattern, 'M') || !str_contains($pattern, 'd'))) {
                throw new InvalidOptionsException(sprintf('The "format" option should contain the letters "y", "M" and "d". Its current value is "%s".', $pattern));
            }

            
/** * @author Pavel Dyakonov <wapinet@mail.ru> */
class UuidType extends AbstractType
{
    /** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->addViewTransformer(new UuidToStringTransformer())
        ;
    }

    /** * @return void */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'compound' => false,
            'invalid_message' => 'Please enter a valid UUID.',
        ]);

    protected static $patterns = [];

    /** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Values used in HTML5 number inputs should be formatted as in "1234.5", ie. 'en' format without grouping,         // according to https://www.w3.org/TR/html51/sec-forms.html#date-time-and-number-formats         $builder
            ->addViewTransformer(new MoneyToLocalizedStringTransformer(
                $options['scale'],
                $options['grouping'],
                $options['rounding_mode'],
                $options['divisor'],
                $options['html5'] ? 'en' : null
            ))
        ;
    }

    /** * @return void */
$parseFormat = 'Y-m-d '.$format;

                $builder->addEventListener(FormEvents::PRE_SUBMIT, static function DFormEvent $event) use ($options) {
                    $data = $event->getData();

                    if (preg_match('/^\d{2}:\d{2}(:\d{2})?$/', $data)) {
                        $event->setData($options['reference_date']->format('Y-m-d ').$data);
                    }
                });
            }

            $builder->addViewTransformer(new DateTimeToStringTransformer($options['model_timezone']$options['view_timezone']$format$parseFormat));
        } else {
            $hourOptions = $minuteOptions = $secondOptions = [
                '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             $emptyData = $builder->getEmptyData() ?: [];

            if ($emptyData instanceof \Closure) {
                $lazyEmptyData = static fn ($option) => static function DFormInterface $form) use ($emptyData$option) {
                    
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\Options;
use Symfony\Component\OptionsResolver\OptionsResolver;

class NumberType extends AbstractType
{
    /** * @return void */
    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']));
        }
    }

    
        $options['first_options']['required'] = $options['required'];
        $options['second_options']['required'] = $options['required'];

        if (!isset($options['options']['error_bubbling'])) {
            $options['options']['error_bubbling'] = $options['error_bubbling'];
        }

        // children fields must always be mapped         $defaultOptions = ['mapped' => true];

        $builder
            ->addViewTransformer(new ValueToDuplicatesTransformer([
                $options['first_name'],
                $options['second_name'],
            ]))
            ->add($options['first_name']$options['type']array_merge($options['options']$options['first_options']$defaultOptions))
            ->add($options['second_name']$options['type']array_merge($options['options']$options['second_options']$defaultOptions))
        ;
    }

    /** * @return void */
    
/** * @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             $emptyData = $builder->getEmptyData() ?: [];

            $yearOptions['empty_data'] = $emptyData['year'] ?? '';
            $weekOptions['empty_data'] = $emptyData['week'] ?? '';

            
$config = new FormConfigBuilder($name$dataClass$this->dispatcher, [
            'error_mapping' => $errorMapping,
        ] + $options);
        $config->setMapped($options['mapped'] ?? true);
        $config->setInheritData($inheritData);
        $config->setPropertyPath($propertyPath);
        $config->setCompound(true);
        $config->setDataMapper(new DataMapper());
        $config->setErrorBubbling($options['error_bubbling'] ?? false);

        if (!$synchronized) {
            $config->addViewTransformer(new CallbackTransformer(
                static fn ($normData) => $normData,
                static fn () => throw new TransformationFailedException()
            ));
        }

        return new Form($config);
    }

    protected function getConstraintViolation($propertyPath$root = null): ConstraintViolation
    {
        return new ConstraintViolation($this->message, $this->messageTemplate, $this->params, $root$propertyPath, null);
    }
$this->registry = $registry;
    }

    /** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if ($options['multiple'] && interface_exists(Collection::class)) {
            $builder
                ->addEventSubscriber(new MergeDoctrineCollectionListener())
                ->addViewTransformer(new CollectionToArrayTransformer(), true)
            ;
        }
    }

    /** * @return void */
    public function configureOptions(OptionsResolver $resolver)
    {
        $choiceLoader = function DOptions $options) {
            // Unless the choices are given explicitly, load them on demand
Home | Imprint | This part of the site doesn't use cookies.