2

I am new in salesforce and I have a requirement to create a trigger on Opportunity to alert the user when an Opportunity is being closed with no Opportunity line items in it.

  • what do you mean alert the user? – Ratan Paul May 4 '16 at 8:41
  • To show error message to user.. – Edna Frank May 4 '16 at 9:11
  • ahh then check Marc's answer that will work for you – Ratan Paul May 4 '16 at 9:15
4

Try this sample of code. It work for me.

trigger opportunitytoopplineitem on Opportunity (before update) {
  map<id,opportunity> allopportunity=new map<id,opportunity>();
 if (Trigger.isBefore && Trigger.isUpdate){

    for (Opportunity oppobj : Trigger.new) {

        if((trigger.oldmap.get(oppobj.id).stagename != 'Closed Won'|| trigger.oldmap.get(oppobj.id).stagename != 'Closed Lost') ){
            if((trigger.newmap.get(oppobj.id).stagename == 'Closed Won'|| trigger.newmap.get(oppobj.id).stagename == 'Closed Lost')){
                allopportunity.put(oppobj.id,oppobj);
            }   
                system.debug('allopportunity@@'+allopportunity);
        }
    }

            if(allopportunity.size()>0){

                for(List<OpportunityLineItem> Oli : [select Description,ListPrice,Name,OpportunityId from OpportunityLineItem where OpportunityId !='' AND OpportunityId In :allopportunity.keySet()])
                {

                    system.debug('oli@@'+oli);
                    if(oli.size() < 1){
                        trigger.new[0].addError('opportunity cannot be closed');
                    }   
                }
            }



 }

}

0

Normally when you ask a question, please do your own research first and post the code you tried so far that it is not working.

Here is a way of achieving you described:

1) First create a rollup summary field on Opportunity which counts the quantity of OpportunityLineItems associated with the related opportunity

2) Here is the basic implementation of the trigger ( although you can do it through a workflow easier)

trigger Opportunity_Line_Items on Opportunity (before insert, before update)
{

   for(Opportunity o: Trigger.new())
   {
        if (o.isClosed==true &&  o.NumberOfOppLineUp__c ==0) {
          o.addError('No Line Items related to this Opportunity');
   }

}
0

The other option would be to create a validation rule to prevent them from closing an opportunity if there are no products on the opportunity. This link is good for some useful validation rules for opportunities Opportunity Validation rules

There is a validation rule on that site for "Opportunity Must Have Products if Beyond “Needs Analysis” Stage"

This can be easily adapted for closed won

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.