I'm having trouble passing through the value of a Lookup field on Insert. I've got an object called ts2__Project_Job__c, which has a custom Lookup field called Candidate__c which looks at the Contact standard object. In my Application I simply want to use this Lookup field, to find a contact, then Insert a new record.
Here's what I've got:
VisualForce
<apex:inputField id="candidate" value="{!contactLookup.Candidate__c}" />
Apex
This is used to get the value:
public ts2__Project_Job__c contactLookup {
get;
set;
}
This is used to instantiate:
contactLookup = new ts2__Project_Job__c();
So far, so good. It creates the Lookup field on the VF Page and it works great! However, when trying to Insert using the following code:
pro.Candidate__c = candidate;
After initialising pro as:
ts2__Project_Job__c pro = new ts2__Project_Job__c();
I get the error:
Illegal assignment from ts2__Project_Job__c to Id
I've tried using
pro.Candidate__c = candidate.Id;
Which will save and create the record, but won't populate the field. Debug logs show that this is blank, whereas the variable candidate does have an Id in there. It's just the wrong type. I've tried using:
Id candidate = String.valueOf(contactLookup);
And passing this through, but nothing happens again.
Kind of stuck on this one!
Thanks!
Edit: When using:
pro.Candidate__c = contactLookup.Id;
I'm getting the following in the debug logs:
System.NullPointerException: Attempt to de-reference a null object
Best Answer
This assignment will always fail:
Any field of type
Id
has to have the correct Id sObject type assigned to it.Here's what I see:
pro
instance ofts2__Project_Job__c
(although you don't show the instantiation, we'll just go with that assumption).pro.Candidate__c
relationship field to candidate data type isId
ofCandidate__c
sObject type.contactLookup
instance ofts2_Project_Job__c
contactLookup.Id
Id ofts2_Project_Job__c
sObject type.Whatever you do, you need to be assigning like for like. Going back to your code:
Here you are trying to assign the
ts2_Project_Job__c
Id value (primary key) to a relationship field that is expecting aCandidate__c
value.You need to assign a
Candidate__c
id value.So that could be:
Or it could be a candidate variable from somewhere else:
It's hard to know without seeing more of your code. But I still get myself twisted around from time to time.
If you have an hour to just learn about how this all works, check out our webinar from September 2014 that did a deep dive on this topic.