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

问题描述 投票:2回答:3

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

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

怎么改呢?

php symfony1 propel
3个回答
3
投票

在检查并设置表单值以执行任何操作后,您可以在表单中覆盖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()
    }

0
投票

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

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

-1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.