本文介绍了Symfony 表单字段属性 empty_data 被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Symfony 2.4 文档,任何不需要但提交时没有任何值的表单字段(选择字段的默认值或文本字段的空值),将被保存到具有 NULL 值的实体.因此,如果您的实体字段被定义为 NOT NULL(例如 not nullable=true),那么当您持久保存实体时,您将收到一个令人讨厌的错误:

According to the Symfony 2.4 Documentation, any form field that is not required, but submitted without any value (default value for choice fields or empty value for text fields), will be saved to the entity with a NULL value. So if your entity field is defined as NOT NULL (e.g. not nullable=true), when you persist the entity you will get a nasty error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'shell' cannot be null

所以文档说如果你不希望它使用 NULL 作为默认值,你可以在文本或选择字段上指定 empty_data 属性.但是,这对我不起作用.

So the documentation says that if you don't want it to use NULL as the default value, you can kindly specify the empty_data attribute on a text or choice field. However, this is not working for me.

实体字段(不可为空):

Entity Field (not nullable):

/**
 * @ORMColumn(type="string")
 */
protected $shell = '';

表单生成器(非必需):

Form Builder (not required):

->add('shell', 'choice', array(
    'label' => 'Shell',
    'choices' => array('shell' => 'Fancy Pants'),
    'required' => false,
    'empty_data' => ''
))

我误解了这个 empty_data 属性吗?我在其他地方错过了一些重要的设置吗?这样做的推荐方法是什么?

Am I misunderstanding this empty_data attribute? Am I missing some important setting elsewhere? What is the recommended way of doing this?

Github 票证 解释说这是 2012 年的一个问题,并且它没有还没有修复.

This Github ticket explains that this was an issue back in 2012, and it hasn't been fixed yet.

这意味着使用表单构建器的每个人都被迫将任何不需要的字段设置为可为空的字段?这对于框架来说似乎很固执……当默认的 '' 或 0 没有唯一含义并且我们不需要 NULL 时,我们不想使用 NULL 有很多原因.对于许多查询,必须同时检查 field=0 或 field=NULL 的存在是一件很痛苦的事情.

That means that everyone who is using the form builder, is forced to make any field that is not required into a nullable field? That seems pretty opinionated for the framework... there are lots of reasons we don't want to use NULL when a default '' or 0 doesn't have unique meaning and we don't need a NULL. For many queries, having to check for the presence of both field=0 OR field=NULL, is a pain.

有其他人正在使用的更好的解决方案吗?

Is there some better solution other people are using?

推荐答案

我按照建议的方式做,但是在 Entity 类中设置了一个默认值.因此,设置 null 的实体正在修复它设置 0 或其他值.

I do it the way suggested, but sets a default value in the Entity class. So insted of setting null the Entity is fixing that it sets 0 or something others.

public function __construct() {
      $this->shell = 0;
}

或者,您可以在 setter 中处理它:

Or, you can take care of it in the setter:

public function setShell($shell) {
      $this->shell = $shell;

      if ( !is_numeric($shell) ) {
             $this->shell = 0;
      }
      return $this;
}

也许不是最佳实践,但它可以不具有可为空的值.

Maybe not the best practice, but It works to not have nullable values.

这篇关于Symfony 表单字段属性 empty_data 被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:52
查看更多