Jeremy Belolo
Jeremy Belolo

Reputation: 4539

Symfony form DateType validation

I have this DateType :

$builder
    ->add('date', DateType::class, array(
        'widget' => 'single_text',
        'format' => 'dd/MM/yyyy',
        "required"=>true,
        'label' => "jour.date"))

When submitting the form with the date being empty, there is no problem whatsoever. It successfully passes

if ($form->isValid())

in the controller, and an error finally pops out with

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'date' cannot be null

The query fails because this can't be null. But I would like it to return the error and not let the form be validated when the date is empty !

As requested, the entity :

/**
 * @var \DateTime
 *
 * @ORM\Column(name="date", type="datetime")
 */
private $date;

Thanks ahead.

Upvotes: 2

Views: 1764

Answers (2)

tinos
tinos

Reputation: 572

From the symfony docs on the required option

This is superficial and independent from validation. At best, if you let Symfony guess your field type, then the value of this option will be guessed from your validation information.

when you call form is valid it relies on the validator service and entity validation mapping to validate your entity.

You need this constraint to set it required

Upvotes: 2

Imanali Mamadiev
Imanali Mamadiev

Reputation: 2654

You have to change:

$builder
->add('date', DateType::class, array(
    'widget' => 'single_text',
    'format' => 'dd/MM/yyyy',
    "required"=>true,
    'label' => "jour.date"))

TO:

$builder
->add('date', DateTimeType::class, array(
    'widget' => 'single_text',
    'format' => 'dd/MM/yyyy',
    "required"=>true,
    'label' => "jour.date"))

Upvotes: 2

Related Questions