问题描述
我有一个包含多个字段的 Symfony2 表单,包括一个名为 recap
的可选文本字段.
I have a Symfony2 form with a variety of fields, including one optional text field called recap
.
这个 recap
字段在其中有一些文本时可以完美保存,但是当该字段留空时,我收到此错误:
This recap
field saves perfectly when there's some text in it, but when the field is left blank, I get this error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'recap' cannot be null
没错 - recap
列不能为 null
.我是故意这样设置的.Null
表示未知.当用户将recap
留空时,recap
的值不是未知的;它是空白的.
That's right - the column recap
can't be null
. I set it that way on purpose. Null
means unknown. When the user leaves recap
blank, the value of recap
is not unknown; it's blank.
我的问题是如何让 Symfony 在空白时将 recap
保存为 ''
,而不是 null
.
My question is how to get Symfony to save recap
as ''
when it's blank, not null
.
推荐答案
转到您的实体并转到变量的声明.
Go to your Entity and go to the declaration of the variables.
/**
* @var string $name
*
* @ORM\Column(type="string", length=50)
*/
public $recap = '';
您可以为 $recap 指定一个默认值.
you can assign a default value for $recap.
或者,当您拥有 setRecap 函数时,您可以检查是否为空或未设置并设置您期望的值.
Or otherway when you have the function setRecap you can check if empty or not set and set the value you expect.
public function setRecap($recap) {
$this->recap = !isset($recap) ? '': $recap;
}
或者您将表单类型中的默认值设置为 '' 但我认为这不是您所期望的.
Or you set the default Value in your form Type to '' but i think then its not what you expect.
这篇关于Symfony2 表单将空白字符串解释为空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!