+ Start a Discussion
TheRiddlerTheRiddler 

Using Triggers to automatically create a contract

When an Opportunity meeting certain criteria is manually closd by a sales person, I would like to have a Contract automatically created and am thinking that a trigger is probably the best way of doing this. Problem being that I am no programmer and looking at the developers guide is like looking at a foreign language text book.

Is building such a trigger a fairly simple exercise and if so, please could some kind soul gently point me in the right direction?

Many thanks.


Best Answer chosen by Admin (Salesforce Developers) 
MaxaMaxa

hi,

is there any way you can paste code for creating new opportunity once, once it been closed won?

All Answers

DevAngelDevAngel
Hi,

Well, to me it seems a fairly easy matter.  As long as you are not intimidated by code you should be able to quite easily implement this. 

Code:
trigger checkOppty on Opportunity(after update) {
  private List<Contract> contracts = new List<Contact>();
  for (Opportunity o in Trigger.new) {
    if (o.isClosed && !Trigger.oldMap.get(o.Id).isClosed) {
      Contract c = new Contract(Name = o.Name);
      contracts.add(c);
    }
  }
  if (contracts.size() > 0) {
    insert contracts;
  }
}
My concern is this might serve to confuse you.

Here goes, triggers are bulk operations.  This means we have to loop through a set of data, even if the set contains just one record.  You can obtain the old and the new value in an after update event. 

The first line creates storage for any contracts we may end up creating. 
The second line begins our iteration of the data that caused the trigger. 
The third line checks to see if the oppty is closed and checks that the old value was not closed (indicating a change from open to closed). 
The fourth line creates a new Contract object setting the name field. 
The fifth line adds this contract to the list of contracts to create. 
The sixth and seventh lines close the if statement and for iteration statement. 
The eigth line checks to see if we have any new contracts to add. 
The ninth line "inserts" the contacts or causes them to be actually created in the database. 
The tenth line closes the if statement. 
The eleventh line closes the trigger class.
 

MaxaMaxa

hi,

is there any way you can paste code for creating new opportunity once, once it been closed won?

This was selected as the best answer