I really need help understanding a trigger i'm trying to code.
I want a trigger who willpopulate the field "What" (field label: "Related to") of an event with the Account's related opportunity when an event is created or updated.
The Trigger is working when I create or update an event in the sandbox. But if I remove the try/catch block, it doesn't anymore for before insert (before update works fine), since an exception is raised:
execution of BeforeInsert caused by: System.QueryException: List has no rows for assignment to SObject.
Why does the trigger have intended behavior with the try/catch block? Any way of removing it?
I know i'm new to coding apex, and did query in a loop, etc. sorry in advance. Best practices tips are appreciated, but please focus on my question.
Any help would be hugely appreciated.
My trigger code:
//logic:
//if name of event is "discovery meeting" or "follow up meeting"
//query account ID on event and store in a variable
//query opportunity related to account
//populate the whatid field of the event with the opportunity ID
trigger Populate_Event on Event (before insert, before update) {
for (Event Meeting : Trigger.new) {
if ((Meeting.subject == 'Discovery Meeting')||(Meeting.subject == 'Follow-up Meeting')){
ID account_id = meeting.accountid;
//need to catch the exception since before insert will fail
try {
opportunity opp = [select id FROM Opportunity Where AccountId = :account_id];
meeting.whatid = opp.id;
}
catch (System.QueryException e) {
System.debug('Catch Query exception');
}
}
}
}
meeting.accountid
populated? It sounds like either triggers are not executing in the order you expect or objects are inserted asynchronously by the app.