0

I have a requirement, where I have the external Id of an Object and would like to fetch other field values in the object using only the External ID but not SOQL query.

The reason I don't want to use SOQL is I am getting a list of external Ids and don't want to use SOQL in for loop. I can use SOQL outside for loop and iterate but looking for a simple process.

Can something like this be achieved in Apex,

Custom_Object__c ob=new Custom_Object__c(External_Id__c='ExternalId');//External Id field
System.debug(ob.Custom_Field__c);

Please help me here

1 Answer 1

1

No, it cannot be done as you suggest.

But if you need to get a list of objects by their External Id, there is no need for SOQL in a loop. Assuming you have a list of external IDs, you can get your objects with just one statement:

List<Id> externalIds; // assuming these are passed from somewhere else
List<Custom_Object__c> objs = [SELECT Id, External_Id__c, Custom_Field__c 
                               FROM Custom_Object__c 
                               WHERE External_Id__c IN :externalIds];

You probably want to get specific objects from this result, so its usually good to put them into a map:

Map<Id, Custom_Object__c> objMap = new Map<Id, Custom_Object__c> ();
for (Custom_Object__c obj : objs) {
    objMap.put (obj.External_Id__c, obj);
}

Then you can directly access a specific object as defined by an external Id using

Custom_Object__c myObject = objMap.get (myExternalId);

and then access the custom field on that:

System.debug (myObject.Custom_Field__c);
3
  • Florian, what I'm trying to understand is without using SOQL, for any object is there a way to get the object fields in a simpler way. I do always go with the above approach you talked about, but is there any other way that can be used? Trying to understand all possible ways.
    – Aryama I
    May 8, 2020 at 11:05
  • You definitely need some kind of query, you have to tell the system what you need. If you construct a new object from an external Id, you can only set certain properties to be changed by an update, but you cannot query properties other then by SOQL or SOSL. May 8, 2020 at 11:11
  • Thank You Florian
    – Aryama I
    May 8, 2020 at 11:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .