【问题标题】:Symfony: save null instead of empty stringSymfony:保存 null 而不是空字符串
【发布时间】:2012-01-06 14:03:55
【问题描述】:

我有一张表,其中一列可以为空。

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

怎么改?

【问题讨论】:

    标签: php symfony1 propel


    【解决方案1】:

    检查并设置表单值后,您可以覆盖表单中的 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()
        }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-04-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-31
          • 2012-07-18
          • 1970-01-01
          • 2011-06-04
          相关资源
          最近更新 更多