setDataMapper example

class ResizeFormListenerTest extends TestCase
{
    private FormFactoryInterface $factory;
    private FormInterface $form;

    protected function setUp(): void
    {
        $this->factory = (new FormFactoryBuilder())->getFormFactory();
        $this->form = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper(new DataMapper())
            ->getForm();
    }

    protected function getBuilder($name = 'name')
    {
        return new FormBuilder($name, null, new EventDispatcher()$this->factory);
    }

    protected function getForm($name = 'name')
    {
        return $this->getBuilder($name)->getForm();
    }


        return new Form($config);
    }

    protected function createBuilder($name$compound = false, array $options = [])
    {
        $builder = new FormBuilder($name, null, new EventDispatcher()new FormFactory(new FormRegistry([]new ResolvedFormTypeFactory()))$options);
        $builder->setCompound($compound);

        if ($compound) {
            $builder->setDataMapper(new DataMapper());
        }

        return $builder;
    }
}
protected EventDispatcher $dispatcher;
    protected FormFactoryInterface $factory;
    protected CsrfTokenManager $tokenManager;
    protected FormInterface $form;

    protected function setUp(): void
    {
        $this->dispatcher = new EventDispatcher();
        $this->factory = (new FormFactoryBuilder())->getFormFactory();
        $this->tokenManager = new CsrfTokenManager();
        $this->form = $this->getBuilder()
            ->setDataMapper(new DataMapper())
            ->getForm();
    }

    protected function getBuilder()
    {
        return new FormBuilder('post', null, $this->dispatcher, $this->factory, ['compound' => true]);
    }

    // https://github.com/symfony/symfony/pull/5838     public function testStringFormData()
    {
        
'a' => 'bar',
                'b' => 'foo',
                'c' => 'baz',
            ],
        ]$this->dataExtractor->extractConfiguration($form));
    }

    public function testExtractConfigurationBuildsIdRecursively()
    {
        $grandParent = $this->createBuilder('grandParent')
            ->setCompound(true)
            ->setDataMapper(new DataMapper())
            ->getForm();
        $parent = $this->createBuilder('parent')
            ->setCompound(true)
            ->setDataMapper(new DataMapper())
            ->getForm();
        $form = $this->createBuilder('name')
            ->setType(new ResolvedFormType(new HiddenType()))
            ->getForm();

        $grandParent->add($parent);
        $parent->add($form);

        
$money = new Money(20.5, 'EUR');
        $factory = Forms::createFormFactoryBuilder()
            ->addExtensions([new ValidatorExtension(Validation::createValidator())])
            ->getFormFactory()
        ;

        $builder = $factory
            ->createBuilder(FormType::class$money['invalid_message' => 'not the one to display'])
            ->add('amount', TextType::class)
            ->add('currency', CurrencyType::class)
        ;
        $builder->setDataMapper(new MoneyDataMapper());
        $form = $builder->getForm();

        $form->submit(['amount' => 'invalid_amount', 'currency' => 'USD']);

        $this->assertFalse($form->isValid());
        $this->assertNull($form->getData());
        $this->assertCount(1, $form->getErrors());
        $this->assertSame('Expected numeric value', $form->getTransformationFailure()->getMessage());
        $error = $form->getErrors()[0];
        $this->assertSame('Money amount should be numeric. "invalid_amount" is invalid.', $error->getMessage());
    }

    
$this->message = 'Message';
        $this->messageTemplate = 'Message template';
        $this->params = ['foo' => 'bar'];
    }

    private function createForm($name = '', $compound = false)
    {
        $config = new FormBuilder($name, null, new EventDispatcher()(new FormFactoryBuilder())->getFormFactory());
        $config->setCompound($compound);

        if ($compound) {
            $config->setDataMapper(new DataMapper());
        }

        return new Form($config);
    }

    // More specific mapping tests can be found in ViolationMapperTest     public function testMapViolation()
    {
        $violation = new ConstraintViolation($this->message, $this->messageTemplate, $this->params, null, 'data', null, null, null, new FormConstraint());
        $form = new Form(new FormConfigBuilder('street', null, new EventDispatcher()));
        $form->submit(null);

        


    protected function getForm($name = 'name', $propertyPath = null, $dataClass = null, $errorMapping = []$inheritData = false, $synchronized = true, array $options = [])
    {
        $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);
    }

    
/** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $unknownValues = [];
        $choiceList = $this->createChoiceList($options);
        $builder->setAttribute('choice_list', $choiceList);

        if ($options['expanded']) {
            $builder->setDataMapper($options['multiple'] ? new CheckboxListMapper() : new RadioListMapper());

            // Initialize all choices before doing the index check below.             // This helps in cases where index checks are optimized for non             // initialized choice lists. For example, when using an SQL driver,             // the index check would read in one SQL query and the initialization             // requires another SQL query. When the initialization is done first,             // one SQL query is sufficient.
            $choiceListView = $this->createChoiceListView($choiceList$options);
            $builder->setAttribute('choice_list_view', $choiceListView);

            


    public function testMapFormsToDataMapsDateTimeInstanceToArrayIfNotSetBefore()
    {
        $propertyAccessor = PropertyAccess::createPropertyAccessorBuilder()
            ->enableExceptionOnInvalidIndex()
            ->getPropertyAccessor();
        $propertyAccessor = PropertyAccess::createPropertyAccessorBuilder()
            ->enableExceptionOnInvalidIndex()
            ->getPropertyAccessor();
        $form = (new FormFactoryBuilder())->getFormFactory()->createBuilder()
            ->setDataMapper(new DataMapper(new PropertyPathAccessor($propertyAccessor)))
            ->add('date', DateType::class[
                'auto_initialize' => false,
                'format' => 'dd/MM/yyyy',
                'html5' => false,
                'model_timezone' => 'UTC',
                'view_timezone' => 'UTC',
                'widget' => 'single_text',
            ])
            ->getForm();

        $form->submit([
            
$builder
            ->setRequired($options['required'])
            ->setErrorBubbling($options['error_bubbling'])
            ->setEmptyData($options['empty_data'])
            ->setPropertyPath($options['property_path'])
            ->setMapped($options['mapped'])
            ->setByReference($options['by_reference'])
            ->setInheritData($options['inherit_data'])
            ->setCompound($options['compound'])
            ->setData($isDataOptionSet ? $options['data'] : null)
            ->setDataLocked($isDataOptionSet)
            ->setDataMapper($options['compound'] ? $this->dataMapper : null)
            ->setMethod($options['method'])
            ->setAction($options['action']);

        if ($options['trim']) {
            $builder->addEventSubscriber(new TrimListener());
        }

        $builder->setIsEmptyCallback($options['is_empty_callback']);
    }

    /** * @return void */
$form->setParent(null);

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

    public function testFormCannotHaveEmptyNameNotInRootLevel()
    {
        $this->expectException(LogicException::class);
        $this->expectExceptionMessage('A form with an empty name cannot have a parent form.');
        $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper(new DataMapper())
            ->add($this->getBuilder(''))
            ->getForm();
    }

    public function testGetPropertyPathReturnsConfiguredPath()
    {
        $form = $this->getBuilder()->setPropertyPath('address.street')->getForm();

        $this->assertEquals(new PropertyPath('address.street')$form->getPropertyPath());
    }

    
$this->validator->validate($formnew Form());

        $this->assertNoViolation();
    }

    public function testValidateChildIfValidConstraint()
    {
        $object = new \stdClass();

        $parent = $this->getBuilder('parent')
            ->setCompound(true)
            ->setDataMapper(new DataMapper())
            ->getForm();
        $options = [
            'validation_groups' => ['group1', 'group2'],
            'constraints' => [new Valid()],
        ];
        $form = $this->getCompoundForm($object$options);
        $parent->add($form);
        $parent->submit([]);

        $this->expectValidateAt(0, 'data', $object['group1', 'group2']);

        
$this->form->get('lastName')->addError(new FormError('Invalid'));

        $this->assertFalse($this->form->isValid());
    }

    public function testDisabledFormsValidEvenIfChildrenInvalid()
    {
        $form = $this->getBuilder('person')
            ->setDisabled(true)
            ->setCompound(true)
            ->setDataMapper(new DataMapper())
            ->add($this->getBuilder('name'))
            ->getForm();

        $form->submit(['name' => 'Jacques Doe']);

        $form->get('name')->addError(new FormError('Invalid'));

        $this->assertTrue($form->isValid());
    }

    public function testSubmitForwardsNullIfNotClearMissingButValueIsExplicitlyNull()
    {
Home | Imprint | This part of the site doesn't use cookies.