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
tjm_pacstratstjm_pacstrats 

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.

Best Answer chosen by Admin (Salesforce Developers) 
hisrinuhisrinu
Tyr this one.

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

hisrinuhisrinu
Tyr this one.

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; } } }

 

This was selected as the best answer
tjm_pacstratstjm_pacstrats
I swear I tried that last night, but then again it was 3am.  Thanks again for your help!