Activity Forums Salesforce® Discussions How can i write a Salesforce trigger for below given scenario ?

  • shariq

    Member
    July 26, 2017 at 12:53 pm

    Hi Aman,

    You can try this :-

    trigger ContactRoleTrigger on Opportunity (after update) {

    List opps = [select stagename,(select id from OpportunityContactRoles) from opportunity where id in:Trigger.new];
    for(Opportunity opp:opps){
    if(opp.OpportunityContactRoles.size() ==0 && opp.StageName=='closed Won'){
    opp.addError('error');
    }
    }
    }

  • Satya

    Member
    January 9, 2018 at 9:02 am

    Hi Shariq,

    I tried your solution in my developer org but it was not working So i have made a minor change in your code and its working fine now.

    so the latest code is :

    trigger ContactRoleTrigger on Opportunity (after update) {

    List<Opportunity> opps = [select stagename,(select id from OpportunityContactRoles) from opportunity where id in:Trigger.new];
    for(Opportunity opp:opps){
    if(opp.OpportunityContactRoles.size() ==0 && opp.StageName==’closed Won’){
    opp.addError(‘error’);
    }
    }
    }

  • Parul

    Member
    September 17, 2018 at 11:43 am

    Hi,

    Here is the code I tried and got success:

    trigger opporTrigger on Opportunity (after update) {

    List<Opportunity> oppor = [select id, name, description, stagename, (select id, name from OpportunityContactRoles) from opportunity where id in: Trigger.new];
    for(Opportunity opp:oppor){
    if(opp.OpportunityContactRoles.size() ==0 && opp.StageName==’closed Won’){
    opp.addError(‘error’);
    }
    }
    }

    Hope this helps you.

    Thanks.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos