Cakephp3:在表单输入中使用 NULL 作为选项

Cakephp3: Using NULL in Form input as options

我正在尝试使用 FormHelper 输入将 null 插入到我的数据库中。

选项应该是:

<?= $this->Form->input('preferedtimeformat', [
        'label' => __('prefered representation of date and time'),
        'options' => [
            NULL => __('standard of your locale'),
            'yyyy-MM-ddThh:mm:ss.sTZD' => __('ISO 8601 (yyyy-MM-ddThh:mm:ss.sTZD)'),
            'eee, dd MMM yyyy hh:mm:ss xx' => __('RFC 2822 (eee, dd MMM yyyy hh:mm:ss xx)'),
            'h:m:s d.M.yyyy' => __('german style (h:m:s d.M.yyyy)'),
            'd.M.yyyy h:m:s' => __('invers german style (d.M.yyyy h:m:s)')
            ...some more options...
        ]
    ]) ?>

这应该可以帮助用户在需要时指定另一种日期时间格式。 Time::i18nFormat() 接受 null 作为日期时间格式,然后使用您为其提供的语言环境预设。

但是从表单创建带有 NULL 选项的用户不起作用,所以我将一个空字符串 ant not null 保存到数据库中。

有没有比在控制器中检查空字符串并将其替换为 NULL 更好的解决方案?

当然你最终会在数据库中得到一个字符串,HTML只能"send"个字符串,PHP接收到的所有输入都是字符串类型,而你的数据库列也是字符串类型。

如果您希望空字符串被视为 NULL,您应该在相应的实体中使用一个变元,它将 '' 变成 null,例如类似

class Xyz extends Entity
{
    protected function _setPreferedtimeformat($value)
    {
        if (empty($value)) {
            return null;
        }
        return $value;
    }
}

另见 Cookbook > Database Access & ORM > Entities > Accessors & Mutators