Basically, I have three custom objects:
Object1__c : Id, Name, Field1__c
Object2__c : Id, Name, Object1__c, Type__c (TypeA,TypeB)
Object3__c : Id, Name, Object2__c
I created custom lookup fields to build relationship among the objects.
Every time a new Object3__c
is inserted, a new Object2__c
must be created. Here's a sample scenario to make things clearer:
Sample Object1__c record :
Object1 Name: ABC
Field1: This is just a sample field.
Sample Object2__c record :
Object2 Name: O2-{00001}
Object1: ABC
Type: TypeA
Sample Object3__c record :
Object3 Name: O3-{00001}
Object2: 02-{00001}
Now, a new Object2__c
record must be created, but this time, Object1__c
lookup field must be ALWAYS equal to this value: DEF
. But remember that this is a lookup field, so I made sure that there's an Object1__c
record with this name:
Sample Object1__c record :
Object1 Name: DEF
Field1: This is a sample field1 value.
Assume that I already have this record. Now, to create new Object2__c
record, I just assigned a Object1__c
field the Id of the above record (DEF record) like this:
o2.Object1__c = 'a0sp0000008zHMw';
But someone told me that this is not a good practice.
How can I handle this kind of scenario without hardcoding the record Id?
Best Answer
If I'm understanding you correctly, you have an object with a lookup field that you always want to associate to the same record. If that is the case, then there must be something distinguishing that record, for example its name. In that case, you would build a query and then reference the returned Id.
It is true that hard-coding an Id is bad practice. Let's look at why. Here are a few scenarios: