1

is there any option to convert an opportunity object into a new contract standard object (and copy some information from the opportunity into the contract)? Is that possible using apex triggers (i.e. when oportunity status is equal to Closed/Won --> Create new Contract object?

2
  • yes through trigger its possible Commented Jan 3, 2014 at 11:56
  • Hello Mohith,could you please, provide me some more details about how it can be done? I have no much experience with APEX. Thanks
    – Guillermo
    Commented Jan 3, 2014 at 11:58

1 Answer 1

4

Yes, you can absolutely accomplish this through an apex trigger.

If you dont have much Apex experience this link will really help to show you some of the best practices when writing triggers

http://wiki.developerforce.com/page/Apex_Code_Best_Practices

As far as the trigger you are looking for, something like this should work

trigger Opportunity_Trigger on Opportunity (after insert) { 

    set<Id> oppIds = new set<id>();
    for(Opportunity o : trigger.new){
        if(o.isWon && !trigger.oldMap.get(o.Id).isWon){
            oppIds.add(o.Id);
        }
    }
    list<Opportunity> myOpps = [Select Id, Name, StageName, OwnerId, AccountId, CloseDate, Amount
                                    From Opportunity 
                                    Where Id In : oppIds];
    list<Contract> newContracts = new list<Contract>();                             
    for(Opportunity o : myOpps){
        //Add whatever information from the opp to the contract that you want here
        myContracts.add(new Contract(
            AccountId = o.AccountId,
            //add more contract attributes here
        ));
    }
    insert newContracts;
}

While this should be a fully functioning trigger, and should work fine. Once you get comfortable writing triggers in this fashion, you might want to look into using another besdt practice for writing triggers, which is keeping the logic of the trigger outside of the trigger itself. There are many frameworks out there for this. Here are just a few

http://developer.force.com/cookbook/recipe/trigger-pattern-for-tidy-streamlined-bulkified-triggers

http://krishhari.wordpress.com/2013/07/22/an-architecture-framework-to-handle-triggers-in-the-force-com-platform/

http://www.tgerm.com/2012/01/salesforce-apex-trigger-template.html

http://wiki.developerforce.com/page/Apex_Enterprise_Patterns_-_Domain_Layer#Trigger_Handling

http://www.embracingthecloud.com/2013/09/06/SalesforceApexWrapperClass.aspx

These are great resources, but I would make sure you are more comfortable with Apex code before trying to jump into these.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .