我正在尝试编写一个适用于几种不同对象类型的通用控制器,但是当我尝试从这些对象访问自定义字段时,出现以下错误:
编译错误:第 33 行第 69 列的通用 SObject 不允许字段表达式
这是我的通用控制器代码:
public with sharing class PhotoUploadController {
public Attachment objAttach{get;set;}
public sObject sobj{get;set;}
public string ObjectName {get;set;}
public Decimal Height{get;set;}
public Decimal Width {get;set;}
Public List<Attachment> lstAttachment {get;set;}
public String setObjectType(sObject newObj)
{
this.ObjectName = newObj.getSObjectType().getDescribe().getName();
return(this.ObjectName );
}
public String getObjectType()
{
return(this.ObjectName);
}
public PhotoUploadController (ApexPages.StandardController controller)
{
objAttach=new Attachment();
lstAttachment= new List<Attachment>();
sobj = controller.getRecord();
if(sobj.id!=null){
sobj = Database.query('select id,name,Image_Attachment_ID__c from ObjectName where id=:sobj.id');
}
if(sobj.Image_Attachment_ID__c!=null){
lstattachment=[SELECT id,body from Attachment where Id=:sobj.Image_Attachment_ID__c limit 1];
if(lstattachment.size()>0)
{
objAttach=lstattachment[0];
}
}
}
public pageReference savePhoto(){
sobj.HeightOfPhoto__c=Height;
sobj.WidthOfPhoto__c=Width;
try {
if (!Schema.sObjectType.sobjectName.isUpdateable())
{
return null;
}
String contentType;
if(objAttach.ContentType !=null){
contentType=objAttach.ContentType;
}
if(contentType !=null && (contentType == 'image/jpeg' || contentType == 'image/CR2' || contentType== 'image/jpg' || contentType== 'image/png' || contentType== 'image/bmp' || contentType== 'image/gif')){
//objAttach.body=body;
//objAttach.name=name;
if(objAttach.body!=null && objAttach.name!=null && sobj.id !=null){
If(objAttach.Id==null)
objAttach.parentId=sobj.id;
if(!Schema.sObjectType.Attachment.isUpdateable()){
return null;
}
try{
upsert objAttach;
sobj.Image_URL__c=URL.getSalesforceBaseUrl().toExternalForm()+'/servlet/servlet.FileDownload?file='+objAttach.id;
sobj.Image_Attachment_ID__c= objAttach.id;
objAttach =null;
if (!Schema.sObjectType.ObjectName.isUpdateable()){
return null;
}
upsert sobj;
}
catch (DMLException e) {
if(e.getMessage().contains('STORAGE_LIMIT_EXCEEDED')){
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Your orgnization Storage Limit has been exceeded, Please contact your Administrator.'));
}else{
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
}
return null;
}finally {
objAttach = new Attachment();
}
}
}
else{
objAttach = new Attachment();
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Please, Upload image file with extension .JPG .JPEG .BMP .PNG or .GIF'));
return null;
}
}
catch(Exception e) {
return null;
}
return new pagereference('/'+sobj.id);
}
}
有人可以更详细地解释此错误消息吗?如何从通用 SObject 类型访问我需要的字段?