function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vikram Singh 157Vikram Singh 157 

i want to update an account name based on their contact where contact first name = null, i am getting error in below code

 Contact C = [SELECT Account.Name FROM contact where FirstName= 'vikky'];    
 C.Account.Name = 'SFDC';
 update C;
 system.debug (C);
system.debug(C.Account.Name);
Best Answer chosen by Vikram Singh 157
Waqar Hussain SFWaqar Hussain SF
Contact C = [SELECT AccountId FROM contact where FirstName= 'vikky'];
Account AccountToUpdate = new Account();
AccountToUpdate.Id = c.AccountId;
AccountToUpdate.Name = 'SFDC';
update AccountToUpdate;

Try above code and let me know If you have any question.

 

All Answers

GauravGargGauravGarg
Hi Vikram,

To make any DML statement on salesforce record you are required to have Unique ID (Salesforce ID). Please query ID and try the same code. 
Contact C = [SELECT Id, Account.Name FROM contact where FirstName= 'vikky'];


Try above query and rerun the code. 

Thanks,

Gaurav
 

Waqar Hussain SFWaqar Hussain SF
Contact C = [SELECT AccountId FROM contact where FirstName= 'vikky'];
Account AccountToUpdate = new Account();
AccountToUpdate.Id = c.AccountId;
AccountToUpdate.Name = 'SFDC';
update AccountToUpdate;

Try above code and let me know If you have any question.

 
This was selected as the best answer
GulshanRajGulshanRaj
Hi Vikram,

For updating account you have to provide object instance of account  with "update" statement instead of contact. 

Here are few suggestion and adjustments:

1) Provide instance of account instead of contact. So, we have
update c.account;
instead of
update c;
This will update contact.

2) Final code:
 
Contact c = [SELECT Id, Account.Name FROM contact where FirstName= 'vikky'];    
c.Account.Name = 'SFDC';
update c.Account;
system.debug (c);
system.debug(c.Account.Name);



If this resolve your problem, please mark this as solved , so that it gets removed from the unanswered queue which results in helping others who are encountering a similar issue.

Thanks & Regards
Gulshan Raj
LinkedIn (https://www.linkedin.com/in/gulshan-raj-a26b0640/)
Twitter (https://twitter.com/gulshan_bittoo)
Vikram Singh 157Vikram Singh 157
Thanks GauravGarg and  Waqar Hussain SF.
Vikram Singh 157Vikram Singh 157

Thnaks Mr. GulshanRaj it works