Symfony表单提交日期至数据库报错:期望string类型,传入了DateTime
I’ve run into this exact issue before, and the problem usually boils down to a mismatch between what your form is passing and what your code expects—even if you didn’t explicitly set a string type anywhere. Here’s how to fix it:
1. Check Your Entity’s Setter Method
The most common culprit is an incorrectly typed setter for your date field. If your entity’s setDate method looks like this:
public function setDate(string $date) { $this->date = $date; }
That’s the problem! The form converts the submitted text into a DateTime object, but your setter is expecting a string. Update it to accept a DateTimeInterface instead:
use DateTimeInterface; public function setDate(?DateTimeInterface $date): self { $this->date = $date; return $this; }
2. Adjust Your DateType Form Configuration
When using widget => 'single_text', it’s good practice to explicitly define the input type and date format to avoid conversion quirks. Modify your FormType code like this:
$builder->add('date', DateType::class, [ 'widget' => 'single_text', 'input' => 'datetime', // Explicitly match your entity's datetime field type 'format' => 'yyyy-MM-dd', // Match the format your frontend uses (HTML5 date inputs default to this) 'html5' => true, // Enable native HTML5 date input for better browser support ]);
Quick Additional Checks
- Make sure you’re not manually converting the
DateTimeobject to a string in your controller before passing it to the entity - Double-check your Doctrine mapping to confirm the field is indeed set to
datetime(you already have this, but it never hurts to verify)
After making these changes, the type mismatch error should disappear.
内容的提问来源于stack exchange,提问作者Marco Koopman

