You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony表单提交日期至数据库报错:期望string类型,传入了DateTime

Fix: "Expected argument of type 'string', 'DateTime' given" When Submitting Symfony DateType to Database

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 DateTime object 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:17:53