【问题标题】:Something strange with blank fields in symfony2 formssymfony2 表单中的空白字段有些奇怪
【发布时间】:2012-04-23 19:56:30
【问题描述】:

当我发送带有空白字段的表单时,我收到错误 SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'image' cannot be null。我发现修复它的唯一方法是在实体文件中设置一个默认值:

 * @ORM\Column(type="string", length=100)
 */
protected $image="";

并像这样更改设置器:

public function setImage($image){
 if(!isset($image)) {
//its really empty but it works only in this way     
}
     else {
    $this->image = $image;
    }  

我觉得这很奇怪... 对此有什么解释吗?还有另一种方法吗? }

【问题讨论】:

  • 属性image 是否是必需的?如果没有,你可以用这个定义代替@ORM\Column(type="string", length=100, nullable=true)
  • 这不是必需的。我提出了您的建议,并更新了架构,并且确实有效。谢谢!
  • 我会把它作为一个答案,所以你可以接受它。

标签: forms symfony doctrine-orm


【解决方案1】:

如果字段image 不是必需的,您可以将其设置为nullable,这样Doctrine 就会知道这一点并将该列设置为可为空。

这样,由于字段可以为空,因此不会违反约束。要使用 Doctrine 注释使字段可为空,只需在 ORM\Column 定义中添加 nullable = true,如下所示:

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

默认情况下,所有列都是nullable=false,因此在尝试将空值持久保存在其中时,它们会抛出一个约束验证异常。

问候,
马特

【讨论】:

  • 但为什么是空文本字段 null 而不是 ""(=空字符串)?
  • 不知道,从来没有挖掘过这一点。也许是 Symfony2 的设计决定。他们可能会通过提供一个选项在表单级别进行自定义...
  • 查看我对“为什么”的回答
【解决方案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

【讨论】:

  • 有趣的,双重马特答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-10
  • 2016-08-14
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多