I have and object 'Car__c' in a package with namespace 'car'. There is a field name 'Price__c' and a lookup field name 'Car_Segment__c'.
To initialize 'Car__c' and assign values to its fields from a class in 'car' package, I am doing something like -
Car__c carobj = new Car__c();
carobj.Price__c = 1000000;
carobj.Car_Segment__c = '0034R00003bVDo1QAG'; // id assignment in this way is for illustration purpose only
There is another package with namespace 'tyre' having an object 'Tyre__c'.
Now I have extended the 'Car__c' object in the other package with namespace 'tyre' by adding an object 'car__Car__c there. There is a requirement to add a lookup to object 'Tyre__c' so I have also added it as a field in my extended object with referenceTo value as -
<referenceTo> tyre__Tyre__c </referenceTo>
I want to assign values to this field too. I am doing something like -
Car__c carobj = new Car__c();
carobj.Price__c = 1000000;
carobj.Car_Segment__c = '0034R00003bVDo1QAG';
//need to check whether the lookup field exists before assigning values
SObject so = Schema.getGlobalDescribe().get('Car__c').newSObject();
if (so.getSobjectType().getDescribe().fields.getMap().containsKey('tyre__Tyre__c')) {
carobj.put('tyre__Tyre__c', '1034R08603bVDo1QAc');
}
insert carobj;
In the second scnario, is this the correct way to initialize the object and assign the values ? If not then can you please suggest a correct and efficient way ?