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
Subrat kumar RaySubrat kumar Ray 

Automatically create opportunitycontactrole with insertion of opportunity in apex

I have a trigger that is checking whether an opportuniycontactrole is created when opportunity is inserted.

trigger OpptyCheck on Opportunity (after insert) {   
List<OpportunityContactRole> oppContRoleList = [Select id, ContactId, OpportunityId from OpportunityContactRole Where OpportunityId IN :trigger.New];
    for(Opportunity opp : trigger.New){
        flag = false;
        for(OpportunityContactRole oppRole : oppContRoleList){
            if((oppRole.OpportunityId == opp.Id){
                flag=true;
            }
        }
        if(!Flag){
            opp.addError('No Active Contact Present. Add an active Contact.');  
        }
    }
}

Problem I am facing now is, whenever trying to insert opp this trigger prevents from insertion.
[except creating opp from contact where opportunitycontactrole will simulatneously created because in url 'ConId' property will hold value of contact ]

Please suggest how to insert an oppty from apex class.

Thanks.
pconpcon
I think there is a flaw in your logic, but I'm having some trouble pulling apart what you are trying to accomplish.  Reading the trigger you will always fail if you have any CpportunityContactRoles already created because you are querying them and then looping through all of the Opportunities and the ContactRoles and finding a match.  If you are trying to see if the role has a contact then you should be setting your flag based on if the contactId field is null or not.

Can you explain a bit more what you are tryting to acomplish?