function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MIDHUN G REDDYMIDHUN G REDDY 

How to Write a Trigger To Create Records

Hi,
How to Write a Trigger To Create Records 
Explain me with code..

Thanks
Midhun
Amit Chaudhary 8Amit Chaudhary 8
Please try below code.
trigger AccountTrigger on Account( after update)
{

	List<Contact> lstCont = new List<Contact>();
	for(Account acc : trigger.new)
	{
		Contact cont = new Contact();
		cont.FirstName = 'Test';
		cont.LastName = 'From trigger';
		cont.email = 'test@test.com';
		lstCont.add(cont);
	}
	if(	lstCont.size() > 0 )
	{
		insert lstCont;
	}

}

If you want to learn how to create trigger. Then please check below post
http://amitsalesforce.blogspot.in/2015/06/trigger-best-practices-sample-trigger.html

Please let us know if this will help you

Thanks
Amit Chaudhary
Ajay K DubediAjay K Dubedi
Hi MIDHUN G REDDY,
Description:
The trigger should 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 opp 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.

Resolution:    
Here is a sample code for reference:
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 : Trigger.new) {
        
        
        // 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 untill 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
        
        vehToInsert.add( v );
        
        
        }//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 );
    }
    
}
To learn the basics of trigger refer to : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers.htm

Thanks.