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
gptheprincegptheprince 

Apex Trigger simple question

Hello
I need some very basic APEX functionalities to support a small non profit project.
Basically what I need to do is to be able to copy some field values from an Contact to 
an Account upon saving the Contact record.
I am in the process of testing/learning how to do this, and I tried creating the trigger 
below, but I always get an error message.
Would anybody help me pointing me in the right direction of what should I chaneg in the sintax
of this code lines?
 
Thanks
******************
trigger ChangeAccountName on Contact (before insert) {
    
Contact[] contacts = Trigger.new;

Contact c = [select account.name from contact where id = :contacts[0].id];

c.account.name='test organization';

update c.account;
}
******************** 
Error Message:
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger AddAccount caused an unexpected exception, contact your administrator: AddAccount: execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.AddAccount: line 10, column 13
ajitvermaajitverma
Hi,

you should fire this trigger after insert event not on before insert,
because contact id is not generated until the row is inserted in the table.
trigger ChangeAccountName on Contact (after insert) {

Contact[] contacts = Trigger.new;

Account ac = [select account.name from contact where id = :contacts[0].id];

ac.name='test organization';

update ac;
}

gptheprincegptheprince

It worked :-)

Thanks a lot for your help

Giorgio