Symfony:保存null而不是空字符串


Symfony: save null instead of empty string

我有一个表,其中一列可以为null。

在symfony中,对于生成的表单,当我将该列的字段留空时,脚本会将空字符串而不是null保存到数据库中。

如何更改?

在检查并设置表单值以执行任何您想要的操作后,您可以覆盖表单中的doSave()函数。

  protected function doSave($con = null) {
    if ($this->getValue('myFormValue') == '') {  // do whatever test you want to determine if the variable should be null
        $this->setMyFormValue(null);  // if it is, set it null
        } 
    parent::doSave($con);  // continue with the parent save()
    }

在Symfony 4中,您可以在表单字段中定义

$formBuilder->add('field_name', TextType::class, [
  'required' => false, // optional
  'empty_data' => '', // it mean if null -> set ''
])

我想你可以这样做:
if (empty($var)) $var = null;