H
H
HellWalk2019-09-05 12:03:21
symfony
HellWalk, 2019-09-05 12:03:21

Why is form-level validation not working?

I do everything according to the official documentation :
Entity

class Passport
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @Assert\NotBlank
     * @ORM\Column(type="string", length=255, nullable=false)
     */
    private $series;

    /**
     * @Assert\NotBlank
     * @ORM\Column(type="string", length=255, nullable=false)
     */
    private $number;

    /**
     * @Assert\NotBlank
     * @ORM\Column(type="date", nullable=false)
     */
    private $issueDate;

    /**
     * @Assert\NotBlank
     * @ORM\Column(type="string", length=255, nullable=false)
     */
    private $issueBy;

//...

PassportType
class PassportType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('series', null, [
                'label' => 'Серия',
            ])
            ->add('number', null, [
                'label' => 'Номер',
            ])
            ->add('issueDate', null, [
                'label' => 'Дата выдачи',
            ])
            ->add('issueBy', null, [
                'label' => 'Кем выдан',
            ])
        ;
    }
//...

test:
public function testFailed(): void
    {
        $entity = new Passport();
        $form = $this->factory->create(PassportType::class, $entity);

        $form->submit([
            'series' => null,
            'number' => null,
            'issueDate' => null,
            'issueBy' => null,
        ]);

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

The test fails because the form thinks everything is valid.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fishernet, 2019-09-18
@Fishernet

try like this:

use App\Entity\Passport;
use Symfony\Component\OptionsResolver\OptionsResolver;
// ...

class PassportType extends AbstractType
{
    // ...

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Passport::class,
        ]);
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question