+ Start a Discussion
krishna chaitanya 35krishna chaitanya 35 

Added a validation rule on opportunity if no primary contact assigned and assigning a primary conatct on contactrole to custom field in opportunity

Hi ,

I have written a trigger on opportunity for counting contcat roles and verifying primary contact assigned or not along with this i am copying the primary contcat in oppcontact role to Custom field in opportunity.Trigger is working fine but only the operation done in opportunity but not in contcatrole.please help to slove this.please find the below code.

trigger Check_Contact_Roles_List on Opportunity(before insert, before update,after insert,after update) {
    Boolean isPrimary;
    Integer iCount;
    //APEX Code
    Map < String, Opportunity > oppty_con = new Map < String, Opportunity > (); //check if the contact role is needed and add it to the oppty_con map
    for (Integer i = 0; i < Trigger.new.size(); i++) {
    isPrimary = False;
    for (List < OpportunityContactRole > oppcntctrle: [select OpportunityId from OpportunityContactRole where(OpportunityContactRole.IsPrimary = True and OpportunityContactRole.OpportunityId in : oppty_con.keySet())]) {
        if (oppcntctrle.Size() > 0) {
            isPrimary = True;
    iCount = 0;
    for (List < OpportunityContactRole > oppcntctrle2: [select OpportunityId from OpportunityContactRole where(OpportunityContactRole.OpportunityId in : oppty_con.keySet())]) //Query for Contact Roles
        if (oppcntctrle2.Size() > 0) {
            iCount = oppcntctrle2.Size();
    for (Opportunity Oppty: system.trigger.new) //Check if  roles exist in the map or contact role isn't required 
        Oppty.Contact_Roles_Counter__c = iCount;
        Oppty.Primary_Contact_Assigned__c = isPrimary;
    if(Trigger.isInsert || Trigger.isUpdate){
         Map<Id, String> mapOppIdWithConLN = new Map<Id,String>();
          for(OpportunityContactRole oCR : [select Id,IsPrimary,Contact.Name, Contact.LastName, OpportunityId From OpportunityContactRole where opportunityId IN : Trigger.new AND isprimary = true]) {
        //Populate map with values
        mapOppIdWithConLN.put(oCR.OpportunityId, oCR.Contact.LastName);
     for(Opportunity opp : Trigger.new) {
        //Check if map contains Opportunity
            opp.Primary_Contact_Name__c = mapOppIdWithConLN.get(opp.Id);