Search code examples
symfonysymfony4symfony-forms

How to make a DateIntervalType field in Symfony form not required


I have a DateIntervalType field:

    $builder
        ->add('effort', DateIntervalType::class, [
            'label' => false,
            'required' => false,
            'widget' => 'integer',
            'input' => 'dateinterval',
            'with_years' => false,
            'with_months' => false,
            'with_days' => false,
            'with_hours' => true,
            'with_minutes' => true,
        ]);

If I submit the form I get the error message that it is invalid if I leave the hours and minutes empty. I have no constraints for the entity attribute (no @Assert\NotBlank() or anything like that) and it is nullable:

class Template
{
    /**
     * @ORM\Column(type="dateinterval", nullable=true)
     */
     private $effort;

    // ...
}

The submitted values are:

"effort" => [▼
    "hours" => ""
    "minutes" => ""
]

I want to submit the form without values and without getting this error.


Solution

  • You do not get errors if you change widget from integer to text:

    $builder
        ->add('effort', DateIntervalType::class, [
            // ...
            'widget' => 'text',
            // ...
        ]);