2012-04-23 71 views
3

当我发送一个空白字段的表单我得到一个错误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 .. 。 这有什么解释吗?还有另一种方法可以做到吗? }

+0

属性'图像'是否需要?如果没有,你可以使用'@ORM \ Column(type =“string”,length = 100,nullable = true)'这个定义。 – Matt 2012-04-23 20:14:03

+0

这不是必需的。我提出了你的建议,并更新了架构,确实有效。谢谢! – s976 2012-04-23 20:25:44

+0

我要让它成为答案,所以你可以接受它。 – Matt 2012-04-23 20:27:19

回答

7

如果不需要现场image,你可以将其设置为nullable这样主义会知道,并会设置列为空。

这样,约束不会被违反,因为该字段可以为空。为了与原则的注释字段为空的,只是在ORM\Column定义,比如添加nullable = true

@ORM\Column(type="string", length=100, nullable=true) 

默认情况下,所有列都nullable=false所以他们将试图在它坚持一个空值时抛出constaint验证异常。

问候,
马特

+1

但为什么是一个空的textfield'null'而不是'“”'(=空字符串)? – apfelbox 2012-04-30 13:19:33

+0

不知道,从来没有挖掘过这一点。也许是Symfony2的设计决定。他们可能可以通过提供一个选项在表单级别自定义... – Matt 2012-05-06 06:07:03

+0

查看我的“为什么”的答案 – Matt 2013-10-01 06:23:06

2

的原因是部分在这里找到答案:

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

+1

有趣,双马特答案:) – Matt 2013-10-01 13:15:42