Skip to content

unsubmitted form doesn't get violation mapped #30011

@videni

Description

@videni

I am not sure if this is a bug, but the behavior looks strange.

CarBrandType

class CarBrandType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('name', FormTypes\TextType::class, [
                'label' => 'acme.car_brand.name.label',
                'required' => true,
            ])
            ->add('enabled',  FormTypes\CheckboxType::class, [
                'label' => 'acme.car_brand.enabled.label',
                'required' => false,
            ])
            ->add('image', FormTypes\TextType::class, [
                'label' => 'acme.car_brand.image.label',
                'required' => false,
            ]);
    }
}

violation rules

Acme\Bundle\AutoBundle\Entity\CarBrand:
    properties:
         name:
            - NotBlank: { groups: ['acme'] }
            - Length: { groups: ['acme'] , max: 40}

Test

I submitted data without the required field name, I can see a violation happened at Symfony\Component\Form\Extension\Validator\EventListener\ValidationListener class, however, calling $form->isValid() will return true, because the Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationMapper doesn't map violation to unsubmitted form. that is the isValid method is not 100% sure the form has no violations. what is the sure way?

 /**
     * @test
     */
    public function it_allows_to_create_a_car_brand()
    {
        $this->client->setServerParameter('HTTP_Authorization', $this->getMainAdminToken());

        $data =
<<<EOT
        {
            "image": "/image_path"
        }
EOT;

        $this->client->request('POST', '/api/admin/car_brands', [], [], ['CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json'], $data);

        $response = $this->client->getResponse();

        $this->assertResponse($response, 'car/brand/create_response', Response::HTTP_CREATED);
    }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions