Skip to content

Instantly share code, notes, and snippets.

@bmodeprogrammer
Created April 22, 2023 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmodeprogrammer/633e53de8f307abceaf2ea8a98e88a12 to your computer and use it in GitHub Desktop.
Save bmodeprogrammer/633e53de8f307abceaf2ea8a98e88a12 to your computer and use it in GitHub Desktop.
get all updatable fields from account and describe it for lwc
public with sharing class AccountsService {
public string getAllFieldsAndValues(String accIdA, String accIdB) {
final Set<String> systemFields = new Set<String> {
'CreatedDate',
'CreatedById',
'LastModifiedById',
'LastModifiedDate'
};
try {
AllFieldsAndValues finalResp = new AllFieldsAndValues();
Map<String, Schema.SObjectField> accountFieldByApiName = Schema.Account.SObjectType.getDescribe().fields.getMap();
String getAccountValuesQuery = 'SELECT {0} FROM Account WHERE Id = {1} OR Id = {2}';
String fields = 'Id, ';
FieldDescription fDesc;
for (String apiName: accountFieldByApiName.keySet()) {
Schema.DescribeFieldResult fieldResult = accountFieldByApiName.get(apiName).getDescribe();
fDesc = new FieldDescription();
fDesc.isSystemField = systemFields.contains(apiName);
if (fieldResult.isAccessible() && (fieldResult.isUpdateable() || fDesc.isSystemField)) {
fields += fieldResult.getType() == Schema.DisplayType.PICKLIST ? ('toLabel(' + apiName + '), ') : apiName + ', ';
fDesc.label = fieldResult.getLabel();
fDesc.apiName = apiName;
fDesc.type = fieldResult.getType().name();
if (fieldResult.getType() == Schema.DisplayType.Reference) {
fDesc.referenceNamePath = apiName.endsWithIgnoreCase('__c') ? apiName.replace('__c', '__r') + '.Name' :
(apiName.endsWithIgnoreCase('__pc') ?
apiName.replace('__pc', '__pr') + '.Name' :
apiName.left(apiName.length() - 2) + '.Name');
fields += fDesc.referenceNamePath + ', ';
fDesc.isReference = true;
}
finalResp.fieldDescriptionByApiName.put(apiName, fDesc);
}
}
String finalQuery = String.format(getAccountValuesQuery, new List<String> {
fields.removeEnd(', '),
'\'' + accIdA + '\'',
'\'' + accIdB + '\''
});
System.debug(finalQuery);
List<Account> accList = Database.query(finalQuery);
finalResp.accountA = accList[0];
finalResp.accountB = accList[1];
return JSON.serialize(finalResp);
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
class AllFieldsAndValues {
public Account accountA;
public Account accountB;
public Map<String, FieldDescription> fieldDescriptionByApiName;
public AllFieldsAndValues() {
fieldDescriptionByApiName = new Map<String, FieldDescription>();
}
}
class FieldDescription {
public String label;
public String apiName;
public String type;
public Boolean isSystemField;
public Boolean isReference;
public String referenceNamePath;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment