symfony2格式的空白字段奇怪
当我发送一个空白字段的表单我得到一个错误SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'image' cannot be null
。要解决这个问题,我发现的唯一方法是使实体文件的默认值:symfony2格式的空白字段奇怪
* @ORM\Column(type="string", length=100)
*/
protected $image="";
,改变这样的setter:
public function setImage($image){
if(!isset($image)) {
//its really empty but it works only in this way
}
else {
$this->image = $image;
}
我认为这是非常starnge .. 。 这有什么解释吗?还有另一种方法可以做到吗? }
如果不需要现场image
,你可以将其设置为nullable
这样主义会知道,并会设置列为空。
这样,约束不会被违反,因为该字段可以为空。为了与原则的注释字段为空的,只是在ORM\Column
定义,比如添加nullable = true
:
@ORM\Column(type="string", length=100, nullable=true)
默认情况下,所有列都nullable=false
所以他们将试图在它坚持一个空值时抛出constaint验证异常。
问候,
马特
的原因是部分在这里找到答案:
Symfony2 forms interpret blank strings as nulls
这段代码获得它周围,因为当Symfony的设置$image
为null,并调用$entity->setImage(null)
,该代码不会改变$image
成员。
public function setImage($image){
if(!isset($image)) {
// $image is null, symfony was trying to set $this->image to null, prevent it
} else {
$this->image = $image;
}
}
这更明确了(谁又想要奇怪的空声明?)。它表达你的意图,即$this->image
不能为空(该数据库定义相匹配,如果你不让它为空的)
public function setImage($image){
if(isset($image)) {
// $image not null, go ahead and use it
$this->image = $image;
}
}
无论哪种方式,你需要初始化$this->image
否则将默认为null
。
有趣,双马特答案:) – Matt 2013-10-01 13:15:42
属性'图像'是否需要?如果没有,你可以使用'@ORM \ Column(type =“string”,length = 100,nullable = true)'这个定义。 – Matt 2012-04-23 20:14:03
这不是必需的。我提出了你的建议,并更新了架构,确实有效。谢谢! – s976 2012-04-23 20:25:44
我要让它成为答案,所以你可以接受它。 – Matt 2012-04-23 20:27:19