0

I'm trying to add an Account id to Contact but when I do the insert and than I check the Contact just created it appear null.

I'm using the following code:

Account Acc = [SELECT id FROM Account WHERE Name = 'pierfrancoForte' LIMIT 1];

Contact c = new Contact(FirstName ='GianPoldo', LastName='Test');
c.Account = Acc;
insert c;

I've also checked the Acc object by debug function and it is not null, but when i check the record on the db it is null: enter image description here

2 Answers 2

1

Try to use the below code

Account Acc = [SELECT id FROM Account WHERE Name = 'pierfrancoForte' LIMIT 1];

Contact c = new Contact(FirstName ='GianPoldo', LastName='Test');
c.AccountId = Acc.Id;
insert c;
2
  • Thanks, now it fill the field but if I can ask you more for the future, Where can I read this field's name? if I go on the field's detail from setup i can see these informations 'Field Information Field Label Account Name Field Name Account Data Type Lookup(Account) Child Relationship Name Contacts' but I cannot see AccountId anywhere, how did you knew it? Again Thanks! Your answer was very helpful
    – demu
    Commented Mar 2, 2017 at 14:40
  • The best way to check the API Name of standard objects/fields is either Force.com IDE or Workbench.
    – RCS
    Commented Mar 2, 2017 at 15:22
1

You have to link the Contact to the Account using the AccountId field. Like this:

Account Acc = [SELECT id FROM Account WHERE Name = 'pierfrancoForte' LIMIT 1];

Contact c = new Contact(FirstName ='GianPoldo', LastName='Test');
c.AccountId = Acc.Id;
insert c;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .