Print this page

Sample Code to create records in APEX and link them to other Objects

Knowledge Article Number 000176618

Sample code to create and link objects using Apex

The trigger will create a new record in a custom object called "Vehicles" when an Opportunity record is created with a specific value in one of its custom fields (the field is called "Type").  So, when an opportunity is created and saved with Type = "x", then the trigger should fire, and a new vehicle object record should be created that is populated with a few fields from that opportunity record.
trigger createVehicleOnOpportunityX on Opportunity (after insert) {
	List <Vehicle__c> vehToInsert = new List <Vehicle__c> 
	// or whatever your custom object name put instead of Vehicle__c
	for (Opportunity o : {
		// here is where you check if opportunity that is being inserted
		//meets the criteria
		if (o.Type__c = "X") {  
		Vehicle__c v = new Vehicle__c (); //instantiate the object to put values for future record
		// now map opportunity fields to new vehicle object that is being created with this opportunity
		v.SomeField__c = o.SomeField__c; // and so on so forth until you map all the fields. 
		//you can also assign values
		v.anotherField__c = "test"; 
		//once done, you need to add this new object to the list that would be later inserted. 
		//don't worry about the details for now
		}//end if
	}//end for o
	//once loop is done, you need to insert new records in SF
	// dml operations might cause an error, so you need to catch it with try/catch block.
	try {
		insert vehToInsert;	
	} catch (system.Dmlexception e) {
		system.debug (e);

promote demote