0

For a visualforce page, in my constructor i'm assigning a variable and retrieving an account from an associated opportunity - when I do a system.debug I get the details I want:

myObject__c myObject = [SELECT etc... ];
System.debug(myObject.opportunity__r.account);

Output:

Account:{Name=Traffic, BillingStreet=Example 34, BillingCity=Example, BillingCountry=Example, BillingPostalCode=D-80807, Website=www.google.com, Id=003N000000iTbKxXXX, CurrencyIsoCode=USD}

But, when I try to save a contact using a save function, and assign this account, the contact is saved, but it doesn't have any account saved to it.

Contact newContact = new Contact();
newContact.FirstName = contactFirstName;
            newContact.LastName = contactLastName;
            newContact.Title = contactJobTitle;
            newContact.Email = contactEmail;
            newContact.Phone = contactPhone;
            newContact.Account = myObject.opportunity__r.account;
            newContact.event__c = myObject.opportunity__r.expo__r.show__c;

            insert newContact;

Everything else is assigned but there is nothing for account, but when I debug the same variable, it displays the required information. Why is this happening?

2

Contact's Account accepts an ID field (the correct field to use is AccountId), try the following query:

Contact newContact = new Contact();
newContact.FirstName = contactFirstName;
        newContact.LastName = contactLastName;
        newContact.Title = contactJobTitle;
        newContact.Email = contactEmail;
        newContact.Phone = contactPhone;
        newContact.AccountId = myObject.opportunity__r.account.Id;
        newContact.event__c = myObject.opportunity__r.expo__r.show__c;

        insert newContact;

You were trying to set the entire Account object to the Contact's Account field.

  • I now have error - illegal assignment from Id to Account --- edit - I wasn't using AccountId. – McH2000 Sep 3 '18 at 11:58
  • Use newContact.AccountId = myObject.opportunity__r.account.Id; instead of newContact.Account – Alberto Sep 3 '18 at 11:58
  • If this answer worked for you, please set it as correct. – Alberto Sep 3 '18 at 11:59
1

You are giving wrong API name here. Correct API name is AccountID. So change this line

newContact.AccountId = myObject.opportunity__r.accountID;
  • 1
    The correct API name of the Contact's Account Id is AccountId. – Alberto Sep 3 '18 at 11:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.