Aura控制器传参至Apex类为空,求助排查方案
问题描述
尝试从Aura控制器调用Apex类方法(组件已设置controller="myController"),代码及问题现象如下:
Aura控制器代码
({ doInit: function (component) { var action = component.get("c.saveRecord"); action.setParams({ record: { Name__c: "Test" } }); action.setCallback(this, function (response) { var state = response.getState(); if (component.isValid() && state === "SUCCESS") { console.log(method + " response:", response.getReturnValue()); } else { console.error("Error while executing " + method, response.getError()); } }); $A.enqueueAction(action); } })
对应Apex类代码
public with sharing class myController { @AuraEnabled public static string saveRecord(namespace__MyCustomRecord__c record) { insert myCustomRecord; return myCustomRecord.Id; } }
问题现象
- 通过Network标签页验证参数已正确发送,但参数到达
saveRecord方法时,record对象为空({}),导致创建的记录除创建人外所有字段为空。 - 该控制器是@RemoteAction旧控制器的副本,旧控制器可正常读写该自定义对象,且控制器属于托管包。
- 已验证自身(系统管理员)拥有字段的查看/编辑权限,尝试JSON编解码方法时出现
No such column 'Name__c' on sobject of type namespace__MyCustomRecord__c错误。
解决思路
修正Apex变量名错误:Apex方法中参数名为
record,但插入的是未定义的myCustomRecord,这会导致插入空对象。修改代码为:@AuraEnabled public static string saveRecord(namespace__MyCustomRecord__c record) { insert record; return record.Id; }统一命名空间前缀:由于是托管包,自定义字段和对象都带有命名空间前缀,Aura传参时必须使用完整的带命名空间的字段名,同时指定
sobjectType:action.setParams({ record: { sobjectType: "namespace__MyCustomRecord__c", namespace__Name__c: "Test" } });托管包内的自定义字段API名称默认包含命名空间,未加前缀会导致Apex无法识别字段,进而无法映射参数。
验证控制器的命名空间引用:如果组件在托管包外部使用,控制器引用需加上命名空间前缀:
controller="namespace.myController";若在包内,确保命名空间引用一致,避免参数映射失败。确认字段API名称准确性:检查
namespace__MyCustomRecord__c对象的字段API名称,确保确实是namespace__Name__c(而非Name__c),JSON编解码的错误提示说明字段名不匹配,需以系统内实际的API名称为准。
内容的提问来源于stack exchange,提问作者Liliyan Krumov
相关产品推荐
相关产品推荐

