You need to sign in to do that
Don't have an account?
System.QueryException: List has no rows for assignment to SObject
I'm trying to write a Trigger that copies the Name of the first contact in the Contact Role into a custom field within the Opportunity in order to automatically name the Opp using a standard naming convention. The problem occurs when there isn't a Contact listed. This is the error message that I receive:
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger SetPrimaryContact caused an unexpected exception, contact your administrator: SetPrimaryContact: execution of BeforeUpdate caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.SetPrimaryContact: line 4, column 20
Here is a copy of my Trigger.
trigger SetPrimaryContact on Opportunity (before update) { for (Opportunity o : Trigger.new) { OpportunityContactRole contactRole; contactRole = [select Contact.Name from OpportunityContactRole where OpportunityId = :o.id order by IsPrimary Desc limit 1]; if(contactRole != null){ o.Primary_Contact__c = contactRole.Contact.Name; } }}
I would want to skip the Trigger if there aren't any Contacts associated with the Account.
Any help would be appreciated.
trigger SetPrimaryContact on Opportunity (before update) { for (Opportunity o : Trigger.new) { List<OpportunityContactRole> contactRole = new List<OpportunityContactRole>(); contactRole = [select Contact.Name from OpportunityContactRole where OpportunityId = :o.id order by IsPrimary Desc limit 1]; if(contactRole.size()>0) { o.Primary_Contact__c = contactRole[0].Contact.Name; } } }
All Answers
trigger SetPrimaryContact on Opportunity (before update) { for (Opportunity o : Trigger.new) { List<OpportunityContactRole> contactRole = new List<OpportunityContactRole>(); contactRole = [select Contact.Name from OpportunityContactRole where OpportunityId = :o.id order by IsPrimary Desc limit 1]; if(contactRole.size()>0) { o.Primary_Contact__c = contactRole[0].Contact.Name; } } }