You need to sign in to do that
Don't have an account?
Getting salesforce ID from SObject?
The idea here is function that can get an array of SObjects and collect the ID of the contact shown in the Contact__c custom field. (lookup field).
This isn't working:
Set<Id> contactIdSet = new Set<Id>(); for (SObject SObj : SObjArr) { sobject Temp = SObj.getSObject('Contact__r'); if (Temp.Id!=null) contactIdSet.add(Temp.Id); }
I tried Temp.get('Id') too, both cause "attempt to de-reference a null" error, which is in my experience the only error I ever get, no matter what the problem.
Can anyone advise me?
Thanks. yeah, I was going to reply with this which took a bit more time because this time around I actually tried it :D
Right, I'm not used to dynamic apex and haven't been actually compiling this in an org before posting. The generic sobject is like a map of string -> object so yes, you will need to cast it to an id like this:
All Answers
How did you populate the SObjArr variable?
It's called from a trigger and passed Trigger.new, in relation to a custom object.
We don't load the related objects in the trigger so asking for the full related SObject will always return null. To get the ID you'll just have to ask for the field, for example:
If you need related objects for additional field data you will need to query for them specifically.
That gives me the error of:
Incompatible element type SObject for collection of Id
how do I make a list of IDs (or strings) if it returns SObjects? this is where I started originally.
Sorry my copy/paste error. Try this:
For reference the list of sobject methods is here in the Apex doc.
I tried that too, buy get is returning an object, not an ID so that still gets the error
Incompatible element type Object for collection of Id
I need it to return ID, or do something to get that id.
got it working!
I needed to use string.valueof!
Thanks. yeah, I was going to reply with this which took a bit more time because this time around I actually tried it :D
Right, I'm not used to dynamic apex and haven't been actually compiling this in an org before posting. The generic sobject is like a map of string -> object so yes, you will need to cast it to an id like this: