You need to sign in to do that
Don't have an account?
Not able to link account and contact objects
Hello All,
I am new to force.com and to Apex and I am still getting settled on this. So pardon me if I ask some naive questions.
I want to link Account and Contact objects. What I mean by that is, when I open a particular Account object, I should be able to see a Contact linked to it.
To accomplish that, I followed a below steps
1. Created a apex class with the following code
public class Assignment {
public static void method1(Account[] acts){
for(Account a : acts){
Contact c = new Contact (lastname='maila', account=a, Birthdate=System.today()-System.today().year()-7000);
insert c;
}
}
}
2. Created a before insert trigger on Accounts, which calls the above class. Code for the trigger is below
trigger GenaricTrigger on Account (after insert) {
Account[] acts=Trigger.new;
Assignment.method1(acts);
}
3. Now I go an create a new Account Object and I expected to see a contact linked to it. But I am not able to find it.
Although a new contact object is been Created, I am not able to link them both.
Thank you folks in advance
--Sunny
Use "accountId" field instead of "account" while inserting contacts.
Contact c = new Contact (lastname='maila', accountId=a.id, Birthdate=System.today()-System.today().year()-700
0);
Also a suggestion. It is always best practice to have a DML operation outside loops. So while creating contacts make a list of contacts collected in for loop and then insert the list outside for loop.
Cheers.
All Answers
Use "accountId" field instead of "account" while inserting contacts.
Contact c = new Contact (lastname='maila', accountId=a.id, Birthdate=System.today()-System.today().year()-700
0);
Also a suggestion. It is always best practice to have a DML operation outside loops. So while creating contacts make a list of contacts collected in for loop and then insert the list outside for loop.
Cheers.
Thank you so much Sarge.
I have accepted you soultion and it works now. I do have a followup question though.
When I look for the fields in Contacts, I donot find the "accountId" fiield. But when I assigned it a value it did accept. How is that possible ?
Does it mean it has fields which are not visible ?
-- Santhosh
Hi Santosh,
In standard objects, the look-up field in apex to another standard object is referred in this way. Hence the Opportunity has Account as a standard field which is lookup, it is again referred in Apex as "accountId" rather "account"