FormError example

return [
            ['text'],
            ['choice'],
        ];
    }

    /** * @dataProvider provideCompoundWidgets */
    public function testYearErrorsBubbleUp($widget)
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create(static::TESTED_TYPE, null, [
            'widget' => $widget,
        ]);
        $form['year']->addError($error);

        $this->assertSame([]iterator_to_array($form['year']->getErrors()));
        $this->assertSame([$error]iterator_to_array($form->getErrors()));
    }

    /** * @dataProvider provideCompoundWidgets */

        $this->serverParams->contentLength = $contentLength;
        $this->serverParams->postMaxSize = $iniMax;

        $options = ['post_max_size_message' => 'Max {{ max }}!'];
        $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, $options);
        $this->setRequestData('POST', [][]);

        $this->requestHandler->handleRequest($form$this->request);

        if ($shouldFail) {
            $error = new FormError($options['post_max_size_message'], null, $errorParams);
            $error->setOrigin($form);

            $this->assertEquals([$error]iterator_to_array($form->getErrors()));
            $this->assertTrue($form->isSubmitted());
        } else {
            $this->assertCount(0, $form->getErrors());
            $this->assertFalse($form->isSubmitted());
        }
    }

    public static function getPostMaxSizeFixtures()
    {
$csrfValue = \is_string($data[$this->fieldName] ?? null) ? $data[$this->fieldName] : null;
            $csrfToken = new CsrfToken($this->tokenId, $csrfValue);

            if (null === $csrfValue || !$this->tokenManager->isTokenValid($csrfToken)) {
                $errorMessage = $this->errorMessage;

                if (null !== $this->translator) {
                    $errorMessage = $this->translator->trans($errorMessage[]$this->translationDomain);
                }

                $form->addError(new FormError($errorMessage$errorMessage[], null, $csrfToken));
            }

            if (\is_array($data)) {
                unset($data[$this->fieldName]);
                $event->setData($data);
            }
        }
    }
}
$label,
                            $translationParameters,
                            $translationDomain
                        );
                    }

                    $message = str_replace('{{ label }}', $label$message);
                    $messageTemplate = str_replace('{{ label }}', $label$messageTemplate);
                }
            }

            $scope->addError(new FormError(
                $message,
                $messageTemplate,
                $violation->getParameters(),
                $violation->getPlural(),
                $violation
            ));
        }
    }

    /** * Tries to match the beginning of the property path at the * current position against the children of the scope. * * If a matching child is found, it is returned. Otherwise * null is returned. */
/** * Abstract class providing test cases for the Bootstrap 5 horizontal Twig form theme. * * @author Romain Monteil <monteil.romain@gmail.com> */
abstract class AbstractBootstrap5HorizontalLayoutTestCase extends AbstractBootstrap5LayoutTestCase
{
    public function testRow()
    {
        $form = $this->factory->createNamed('')->add('name', TextType::class);
        $form->get('name')->addError(new FormError('[trans]Error![/trans]'));
        $html = $this->renderRow($form->get('name')->createView());

        $this->assertMatchesXpath($html,
            '/div [@class="mb-3 row"] [ ./label [@for="name"] [@class="col-form-label col-sm-2 required"] /following-sibling::div [@class="col-sm-10"] [ ./input[@id="name"] /following-sibling::div [@class="invalid-feedback d-block"] [.="[trans]Error![/trans]"] ] [count(./div)=1] ] '

    public function testValidationShouldFail(string $expectedValueParameterValue, ?string $submittedValue, bool $trim = true)
    {
        $form = $this->factory->create(static::TESTED_TYPE, null, [
            'html5' => true,
            'trim' => $trim,
        ]);

        $form->submit($submittedValue);

        $expectedFormError = new FormError('This value is not a valid HTML5 color.', 'This value is not a valid HTML5 color.', [
            '{{ value }}' => $expectedValueParameterValue,
        ]);
        $expectedFormError->setOrigin($form);

        $this->assertEquals([$expectedFormError]iterator_to_array($form->getErrors()));
    }

    public static function validationShouldFailProvider()
    {
        return [
            ['foo', 'foo'],
            [
namespace Symfony\Bridge\Twig\Tests\Extension;

use Symfony\Component\Form\FormError;
use Symfony\Component\Security\Csrf\CsrfToken;

abstract class AbstractDivLayoutTestCase extends AbstractLayoutTestCase
{
    public function testRow()
    {
        $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
        $form->addError(new FormError('[trans]Error![/trans]'));
        $view = $form->createView();
        $html = $this->renderRow($view);

        $this->assertMatchesXpath($html,
            '/div [ ./label[@for="name"] /following-sibling::ul [./li[.="[trans]Error![/trans]"]] [count(./li)=1] /following-sibling::input[@id="name"] ] '

            'errors' => [],
            'synchronized' => true,
        ]$this->dataExtractor->extractSubmittedData($form));
    }

    public function testExtractSubmittedDataStoresErrors()
    {
        $form = $this->createBuilder('name')->getForm();

        $form->submit('Foobar');
        $form->addError(new FormError('Invalid!'));

        $this->assertSame([
            'submitted_data' => [
                'norm' => 'Foobar',
            ],
            'errors' => [
                ['message' => 'Invalid!', 'origin' => spl_object_hash($form), 'trace' => []],
            ],
            'synchronized' => true,
        ]$this->dataExtractor->extractSubmittedData($form));
    }

    
'csrf_message' => '[trans]Foobar[/trans]',
                'csrf_token_id' => 'TOKEN_ID',
                'compound' => true,
            ])
            ->getForm();

        $form->submit([
            'csrf' => 'token',
        ]);

        $errors = $form->getErrors();
        $expected = new FormError('[trans]Foobar[/trans]', null, [], null, $csrfToken);
        $expected->setOrigin($form);

        $this->assertGreaterThan(0, \count($errors));
        $this->assertEquals($expected$errors[0]);
    }
}
namespace Symfony\Bridge\Twig\Tests\Extension;

use Symfony\Component\Form\FormError;
use Symfony\Component\Security\Csrf\CsrfToken;

abstract class AbstractTableLayoutTestCase extends AbstractLayoutTestCase
{
    public function testRow()
    {
        $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType');
        $form->addError(new FormError('[trans]Error![/trans]'));
        $view = $form->createView();
        $html = $this->renderRow($view);

        $this->assertMatchesXpath($html,
            '/tr [ ./td [./label[@for="name"]] /following-sibling::td [ ./ul [./li[.="[trans]Error![/trans]"]] [count(./li)=1] /following-sibling::input[@id="name"] ] ] '
$data = $request->query->all()[$name];
            }
        } else {
            // Mark the form with an error if the uploaded size was too large             // This is done here and not in FormValidator because $_POST is             // empty when that error occurs. Hence the form is never submitted.             if ($this->serverParams->hasPostMaxSizeBeenExceeded()) {
                // Submit the form, but don't clear the default values                 $form->submit(null, false);

                $form->addError(new FormError(
                    $form->getConfig()->getOption('upload_max_size_message')(),
                    null,
                    ['{{ max }}' => $this->serverParams->getNormalizedIniPostMaxSize()]
                ));

                return;
            }

            if ('' === $name) {
                $params = $request->request->all();
                $files = $request->files->all();
            }

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function DFormEvent $event) use ($request) {
            if ($request->attributes->has(SecurityRequestAttributes::AUTHENTICATION_ERROR)) {
                $error = $request->attributes->get(SecurityRequestAttributes::AUTHENTICATION_ERROR);
            } else {
                $error = $request->getSession()->get(SecurityRequestAttributes::AUTHENTICATION_ERROR);
            }

            if ($error) {
                $event->getForm()->addError(new FormError($error->getMessage()));
            }

            $event->setData(array_replace((array) $event->getData()[
                'username' => $request->getSession()->get(SecurityRequestAttributes::LAST_USERNAME),
            ]));
        });
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        /* Note: the form's csrf_token_id must correspond to that for the form login * listener in order for the CSRF token to validate successfully. */
/** * Abstract class providing test cases for the Bootstrap 4 Twig form theme. * * @author Hidde Wieringa <hidde@hiddewieringa.nl> */
abstract class AbstractBootstrap4LayoutTestCase extends AbstractBootstrap3LayoutTestCase
{
    public function testRow()
    {
        $form = $this->factory->createNamed('name', TextType::class);
        $form->addError(new FormError('[trans]Error![/trans]'));
        $view = $form->createView();
        $html = $this->renderRow($view);

        $this->assertMatchesXpath($html,
            '/div [ ./label[@for="name"] [ ./span[@class="alert alert-danger d-block"] [./span[@class="d-block"] [./span[.="[trans]Error[/trans]"]] [./span[.="[trans]Error![/trans]"]] ] [count(./span)=1] ] /following-sibling::input[@id="name"] ] '
public function testInvalidIfChildIsInvalid()
    {
        $this->form->add($this->getBuilder('firstName')->getForm());
        $this->form->add($this->getBuilder('lastName')->getForm());

        $this->form->submit([
            'firstName' => 'Bernhard',
            'lastName' => 'Schussek',
        ]);

        $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'))
            
$formBuilder = new FormBuilder(
            'form',
            null,
            new EventDispatcher(),
            new FormFactory(new FormRegistry([]new ResolvedFormTypeFactory())),
            []
        );

        $form = $formBuilder->getForm();

        $cause = new ConstraintViolation('Error 1!', null, [], null, '', null, null, 'code1');
        $form->addError(new FormError('Error 1!', null, [], null, $cause));
        $cause = new ConstraintViolation('Error 2!', null, [], null, '', null, null, 'code1');
        $form->addError(new FormError('Error 2!', null, [], null, $cause));
        $cause = new ConstraintViolation('Error 3!', null, [], null, '', null, null, 'code2');
        $form->addError(new FormError('Error 3!', null, [], null, $cause));
        $formErrors = $form->getErrors();

        $specificFormErrors = $formErrors->findByCodes($code);
        $this->assertInstanceOf(FormErrorIterator::class$specificFormErrors);
        $this->assertCount($violationsCount$specificFormErrors);
    }

    
Home | Imprint | This part of the site doesn't use cookies.