Play Games

Search This Blog

Friday, March 9, 2018

How to get Unique Id fields of an object in Apex

Solution: We can check if a field is unique field by using isUnique() of Schema.DescribeFieldResult.

Sample Apex Code:
In this example We have a custom field 'Unique__c' field created on lead object which is made unique by clicking unique Id checkbox.

List<String> lstUniqueField = new List<String>();
Map<String, Schema.SObjectField> describeFields = Schema.SObjectType.Lead.fields.getMap();
for(String field : describeFields.keyset()){
Schema.DescribeFieldResult desribeResult = describeFields.get(field).getDescribe();
if(desribeResult.isUnique()) {
lstUniqueField.add(field);
}
}
System.debug('Unique fields of Lead Object'+lstUniqueField );

Output:


How to get external Id fields of an object in Apex

Solution: We can check if a field is externalId field by using isExternalId() of Schema.DescribeFieldResult.

Sample Apex Code:
In this example We have a custom field 'lead_external_id__c' field created on lead object which is made external by clicking external Id checkbox.

List<String> lstExternalField = new List<String>();
Map<String, Schema.SObjectField> describeFields = Schema.SObjectType.Lead.fields.getMap();
for(String field : describeFields.keyset()){
Schema.DescribeFieldResult desribeResult = describeFields.get(field).getDescribe();
if(desribeResult.isExternalId()) {
lstExternalField.add(field);
}
}
System.debug('ExternalId fields of an Lead object'+lstExternalField);

Output: