Winter’21升级导致Aura的createRecordEvent中Datetime赋值行为变化

众所周知,Winter‘21在发布此文时已经正式上线。
其中,由于对Aura中使用Apex的权限采取了更严格的标准,从而导致了大批功能崩溃的惨剧。

除此之外,还有另一个Aura的底层变化也值得注意。
在最新的文档中,force:createRecord这个event的文档下面增加了一行小字

Date and time field values must use the ISO 8601 format. For example:

Date: 2017-07-18
Datetime: 2017-07-18T03:00:00Z
While the create record panel presents datetime values in the user’s local time, you must convert datetime values to UTC to prepopulate the field.

这就导致了原来直接向Datatime字段赋值Date值的功能报错。

	let createRecordEvent = $A.get("e.force:createRecord");
        createRecordEvent .setParams({
            "entityApiName": "A__c",
            "defaultFieldValues": {
                'testDatetime__c' : '2020-10-21'
            }
        });
        createRecordEvent .fire();
// Error on Save : Value for field 'testDatetime__c' is not in ISO 8601 format, Value: 2020-10-21, Runtime class: java.lang.String

保存数据时会报如下错误

Error: Value for field ‘testDatetime__c’ is not in ISO 8601 format, Value: 2020-10-21, Runtime class: java.lang.String

如果有需要把date值写入datetime型字段的同学,可以在helper添加如下方法为date值填充时分秒,以此伪装成datatime值。

    // in helper
    paddingTime : function(date) {
        if(date != "" && date != null && date != undefined && date != {}) {
            date = date + "T00:00:00.000";
        }
        return date;
    }

    // in controller
    init : function(component, event, helper) {
        let createRecordEvent = $A.get("e.force:createRecord");
        createRecordEvent .setParams({
            "entityApiName": "A__c",
            "defaultFieldValues": {
                'testDatetime__c' : helper.paddingTime('2020-10-21')
            }
        });
        createRecordEvent .fire();
     }

另外需要值得注意的是,虽然aura的controller看起来是前端,但实际上createRecord事件的日期时间赋值行为等同于Apex————既作为UTC时间插入数据库,需要考虑显示时差问题。

那么相比之下,有同学会产生疑问,Apex受影响吗? 还能愉快的直接将date值写入datetime型字段吗?
答案是,放心,Apex一如既往。

// 后记
其实我并不确定官方文档里关于时期格式的描述一定是Winter’21后才加的,但是很确定Winter’21之前可以直接把date值赋给datetime型字段。毕竟aura event的文档无法查看历史版本,所以,就让我主观的视其为Winter’21吧。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据