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
RossGilbertRossGilbert 

apex trigger that creates a new record

OK so I've been an admin for about 3 years and (for better or worse) know more about SF than anyone in my company.  i have some experience with apex and Visualforce, but little with triggers.

 

what i need is to write a trigger in production that does this:  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.

 

can anyone send me some code to show me what this trigger should be or look like?  I've been researching this but have no clue, and I'm afraid of writing bad code that will cause problems.

 

also, the custom object is not in a parent-child relationship with the opporuntiy object, and i don't want it to be unless it has to be.

 

i know the developers in here are ridiculously smart and talented, and i'm just hoping one of you feels sorry enough for an amateur like me to help me out.  thanks a lot.

Best Answer chosen by Admin (Salesforce Developers) 
orikkerorikker

That works for me.  I guess I could have thought of that. You should just register a new dev org, so we can collaborate there and then just abandon it :)  I'll shoot you a private message with my info. Please mark this post as solved (i think it is ) :)

All Answers

joshbirkjoshbirk

Have you seen the workbook chapter on triggers?

 

http://www.salesforce.com/us/developer/docs/workbook/Content/apex_intro.htm

orikkerorikker

Wow, way to answer, Admin! just what SFDC support team always does - points to the obvious. Oh well....

 

Here you go, pal. see notes below.

 

 

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);
	}
	
}

 

This trigger will only fire on new opportunities. updating type field on existing records will not refire it. Not sure why you wont want to relate to objects, but it is up to you, I don't know your business requirements. Let me know if you get stuck with the code. Try it in sandbox, because for prod you will need some test coverage, which I can show you once you master this. Have fun!

 

 

 

bob_buzzardbob_buzzard

Now now Orikker.  Lets not start sniping at people who give up their own time to post a reply that they believe will help.

 

 

orikkerorikker
  nothing against regular contributors, but this guy is SFDC admin, people who are paid to sit here and help. Any time I have an issue and I open a case with SF, all they do is point me to their manual... I know it inside out and the only time I submit a case is when there is a bug in the system, but they don't even take time to study it, just shoot me with canned responses... Again, I appreciate help and time all the regular contributors give to this community. I myself try to help as much as I can as you can see from the post :) Let me know if I am wrong about the admin guy. I will apologize if he indeed does it on his own time....
bob_buzzardbob_buzzard

I'd imagine that the Salesforce bods aren't paid to come on these boards, as otherwise there would be hundreds of them wouldn't there?  Maybe one of them will let us know either way.

 

I'm sure we've all had varying experiences with support - I know I have and have obliquely mentioned it in posts (e.g. posting here as a last resort etc).  However, I don't feel that this is the right place to take shots at SFDC.  If a post isn't helpful its better just to skip over it and try to provide something better - as you have done and I'm sure the original OP appreciates.

 

One of the finer aspects of these boards is the positive attitude that prevails and I for one am extremely keen to keep it that way - probably because I used to frequent the JBoss boards years ago where admins and "experts" used to ask new users why they didn't go and learn some basics before posting stupid questions and wasting everyone's time. 

 

 

orikkerorikker

:) right on. Are you the guy from SF bingo @DF2010?

bob_buzzardbob_buzzard

Hah - I originally read that as "are you the guy from SF" - getting all ready to display my independence :)

 

I don't actually know - I was at DF 2010 - didn't get to see anything bingo related.

joshbirkjoshbirk

Technically you're both somewhat right.  I'm a Dev Evangelist here at Salesforce, so spending time on the boards is under my job title as part of community development.  Not in the same group that handles support cases, however.  I was browsing the forums last night looking for some lonely unanswered questions.

 

My aim wasn't to be canned, it was pointed to the fact that it seemed the OP was having troubles finding documentation and best use cases on writing triggers more than Apex itself, and as the Workbook chapter is under "adding business logic", it can be a little hard to find - but is a great primer in getting started with triggers.

 

But let's not get off topic here, let's keep the thread clear for the OP to ask any follow up question.  Either of you guys can feel free to email me directly if you like.  Look forward to seeing you around the community.  

RossGilbertRossGilbert

You guys are amazing.

 

So, I took the code you provided and started trying to input it in as a new trigger in the opportunity object in my sandbox.  I get the following error message when I try to save this trigger.  Any idea what the solution is?  I also highlighted one of your comments in red below that I simply don't understand at all.  Would you mind explaining what you mean in that comment?

 

Here's the error message:

 

Error: Compile Error: line 11:21 no viable alternative at character '"' at line 11 column 21

 

 

Here's my trigger:

 

 

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 = "NS-TO (New Sale - Task Order Contract)") {  
        
        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.Name = o.Name; // and so on so forth untill you map all the fields. 
        
        //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);
    }
    
}

 

 

joshbirkjoshbirk

Try using single quotes - Apex dislikes the double quotes.  Also, you need that line to evaluate, so use double equals as the operator, i.e.:

 

if (o.Type == 'NS-TO (New Sale - Task Order Contract)')

 

 

orikkerorikker

My bad Ross :) 

RossGilbertRossGilbert

yep you solved that problem.  thanks a lot.  i now get this error message though:

 

Error: Compile Error: unexpected token: 'for' at line 6 column 4

 

Here's  the most updated code, using your single quotes and double equals suggestion, which resolved my first error message:

 

 

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 == 'NS-TO (New Sale - Task Order Contract)')
        
        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.Name = o.Name; // and so on so forth untill you map all the fields. 
        
        //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);
    }
    
}

 

 

 

 

RossGilbertRossGilbert

orikker and josh...i just want to say THANK YOU so much to both of you.  i'm hoping this little exercise teaches me how to start writing triggers on my own.  i wouldn't even be able to begin without you guys.  seriously.  thanks.

orikkerorikker
if (o.Type == 'NS-TO (New Sale - Task Order Contract)'){

 

it looks like I missed { after if statement

 

try

 

 

RossGilbertRossGilbert

Thanks orikker.  I'm not sure I follow your suggestion though.  What are you saying I should do?  Thanks again I really appreciate it.

orikkerorikker

you are missing a curly bracket at the end of the line with "IF" statement. add { to the end of the line.

RossGilbertRossGilbert

thanks orriker.  I'm still getting the error message:

 

Error: Compile Error: unexpected token: 'for' at line 6 column 4

 

any idea what is wrong with the code below?  thanks again.

 

here's the most current version of the code, including your changes:

 

 

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 == 'NS-TO (New Sale - Task Order Contract)') {
        
        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.Name = o.Name; // and so on so forth untill you map all the fields. 
        
        //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);
    }
    
}

 

 

 

orikkerorikker

List <Vehicle__c> vehToInsert = new List <Vehicle__c>  (); 

 

not sure if I missed it or you did. try it.

 

RossGilbertRossGilbert

dude...can i nominate you for an award or something?  you are the MAN.  this trigger is working in my sandbox now.  I'm testing it out but it is working.

 

so, now when an opp is created and saved with Type=x, a vehicle custom object record is created, which is exactly what i need.  it populates with fields from the opp.  just AWESOME. 

 

i think at this point i need to do just 2 things to get this in production:

 

1. on the opportunity page layout there's a lookup field to the Vehicle custom object.  I want that field to populate with the record name of the new Vehicle record that our trigger (your trigger, really) creates when the opp is created.  I don't think i can do this with workflow rule/field update.  I'm thinking maybe we can add a line of code in the trigger that, when the opp is created and saved, populates that lookup field with the vehicle record.

 

For example, the way the trigger works now: opportunity named "X" is created and saved.  the trigger auto creates a new vehicle record with the same name as the opp.  what i want is, when the user creates opp "X" and clicks save, the opp populates the vehicle lookup field with the name of the newly created vehicle record.  any idea if we can add a line of code to the trigger to do that?

 

2. implementing the trigger in production.  i might be able to figure this out, but any advice on how to properly start doing this is appreciated. greatly.

 

again, thank you.  i don't know what i would do without this site and specifically, orikker's help. 

orikkerorikker

Thanks Dude :)

 

Here is my question before we go any further. Why is the look up you have is on the opportunity page and not on vehicle? Since you are adding vehicle to the opportunitie, it would be logical to have a look up on the vehicle to the loan. Maybe I am messing up your requirements (or simply don't understand).

 

Think of it this way - you create a vehicle for some opportunities. so one opportunity might have more then one vehicle (hypothetically someone can by more than one car), but it is hardly unlikely that same car is bought by two opportunities.  So look up should be on the opp and not on veh. this way you can see all veh on the related list on the opp. Let me know if your requirements are actually the other way around :)

 

As far as production roll out, you will need two things : Force.com IDE to upload code and test apex class to have at least 75% code coverage. We can cover that when you are done with sandbox.

RossGilbertRossGilbert

thanks orikker.  i think the custom object name "Vehicle" might be misleading.  it's not a vehicle like a car, which I think you might be lead to believe by the information I've provided. a vehicle in the context of our SF instance is a record that can have several opportunities associated with it.  There's a vehicle related list in our vehicle object showing any opps assigned to that vehicle record.

 

All I need the trigger to do now, and maybe there is some other way to do this that you can recommend, is populate the newly created vehicle record name in the newly created opp.  so when the user clicks save on the new opp and it saves, the new vehicle record is created, and the opp is updated with the name of that new vehicle.  again, not sure if this is possible, but i suspect it is.

 

thanks again

RossGilbertRossGilbert

also thanks r.e. Eclipse IDE.  I had that on my old computer and used it for very basic stuff like new custom object and field creation, but have no experience with it beyond that.  also the word "class" strikes fear into my heart (as does the word trigger, though less so now thanks to you).

orikkerorikker

The name is indeed misleading :)

 

The second part (attaching opportunity to vehicle) is quite tricky, it would be faster and more productive if you let me do it in your sandbox, this way we don't have to post bunch of threads about code errors :) let me know if you are interested, I don't mind helping.

 

RossGilbertRossGilbert

thanks orikker.  i set up this trigger in a sandbox for my company's sandbox.  what i think i will do is replicate what i did in my developer edition, then give you access to that.  that way i can avoid any issues with security, if you know what i mean.  thanks a lot.  i'm literally without words to describe how helpful you are.  i hope someone is paying you a LOT of money to do this stuff somewhere.

orikkerorikker

That works for me.  I guess I could have thought of that. You should just register a new dev org, so we can collaborate there and then just abandon it :)  I'll shoot you a private message with my info. Please mark this post as solved (i think it is ) :)

This was selected as the best answer
RossGilbertRossGilbert
great thanks!
hickmand1hickmand1

I have replicated the same code but am getting the following error message

 

"Error: Compile Error: Method does not exist or incorrect signature: AMS_Leads__c() at line 6 column 26"

 

It should work fine as it mirrors (for the most part) what you've done..but it keeps giving me an error  for the line

 

what am I missing?

                     

Trigger createAMSLead_c on Lead (after insert) {

       List <AMS_Leads__c> AMSLeadsInsert = new List <AMS_Leads__c> ();

        for (Lead o : Trigger.new) {  

  if (o.newLead.LeadSource !== 'Web') {

        AMS_Leads__c v = AMS_Leads__c ();

 

        v.Campaign_Lead_Info__c = o.Name;

        v.Email_Address__c = o.Lead.Email;

        v.Notes__c = o.Lead.Description;

        v.Home_Work__c = o.Lead.Phone;

        v.Cell_Phone__c = o.Lead.MobilePhone;

        v.Date_Time_of_Response__c = system.NOW();

        v.Follow_Up_Method__c = 'Telephonic - Outsource';

       

             

        AMSLeadsInsert.add(v);

       

       

        }

       

    }

       try {

        insert AMSLeadsInsert;

    } catch (system.Dmlexception e) {

        system.debug (e);

        }

        }

     

 

hickmand1hickmand1

Apologies made a few other corrections but still end up with the error

 

 Error: Compile Error: Expression cannot be assigned at line -1 column -1


Trigger createAMSLead_c on Lead (after insert) {

   

    List <AMS_Leads__c> AMSLeadsInsert = new List <AMS_Leads__c> ();

        for (Lead o : Trigger.new) {

        if (Lead.LeadSource = 'Web') {

        AMS_Leads__c v = new AMS_Leads__c ();

        v.Campaign_Lead_Info__c = o.Name;

        v.Email_Address__c = o.Email;

        v.Notes__c = o.Description;

        v.Home_Work__c = o.Phone;

        v.Cell_Phone__c = o.MobilePhone;

        v.Date_Time_of_Response__c = system.NOW();

        v.Follow_Up_Method__c = 'Telephonic - Outsource';

       

              

        AMSLeadsInsert.add(v);

       

       

       }

      

    }

        try {

        insert AMSLeadsInsert;

    } catch (system.Dmlexception e) {

        system.debug (e);

        }

hickmand1hickmand1

Never mind....all solved!

ForstaForsta

I tweated the code to create a new contact when a SFDC user (standard) is created but it doesn't do anything. Any ideas on how to fix this:

 

trigger CreateUserContact on User (after insert) {
    List<Contact> userContact = new List<Contact>();

    //For each position processed by the trigger, add a new 
    //interviewer record for the specified hiring manager. 
    //Note that Trigger.New is a list of all the new positions 
    //that are being created. test
     
    for (User u: Trigger.New) {
                if (u.usertype == 'standard'){
                Contact c = new Contact ();
                c.FirstName = u.FirstName;
                c.Title = u.Title;
                c.ownerid='00580000003C9gf';
        
           userContact.add(c);
                   }//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 userContact; 
    } catch (system.Dmlexception e) {
        system.debug (e);
    }
    
}

 Thanks

daniel1110daniel1110

Hi orikker,

 

thank you for your posts, it's been very helpful. i have slightly a separate requirement:

 

how would the code change if you want to fire the trigger on update field on existing records?

 

daniel

pratik.prusty1.3926473648707793E12pratik.prusty1.3926473648707793E12
Hi Daniel/Orikker,

I too have more or less the same requirement where I need to create a record in a custom obj according to some field values in case object . Futher to that any updation on the case should also reflect on the new record that got created in the custom object.
Please help with some snippets or anyhting of that sort.

Thanks in advance.


regards,
Pratik
ventoreroventorero
For what its worth. this article really saved me alot of time. i guess that it narrowed my work to 1 hour including the test class. Orikker thank you, your willingness to help others worth gold.
Brianne BeattyBrianne Beatty
Help with my error, pls. Thx.

I've read through this thread and Im stuck at one error. I know a little programming so I'm really stumped ....

I'm trying to create a new record in my custom Obj "RoundRobin" when a new case is created and the assignment rules assign the Case to our "Support Queue" .. We have 7 different record types total for cases but only 5 get assigned to the Support Queue.
I am trying to create a Round Robin within the queue.
My logic:
Create new RoundRobin record when a case get's assigned to the Support Queue
Increment the custom RoundRobin field, RR Count Increments (type: number)
Continue using this process: How do I create a round-robin assignment for Leads or Cases to users (https://help.salesforce.com/apex/HTViewSolution?id=000004000)

But I can't even get my trigger to work: Create new RR record when Case Owner = Support Queue


Error: Compile Error: expecting a semi-colon, found ')' at line 6 column 30

trigger createRRx on Case (after insert) {
    
    List <RoundRobin> RRIncrements = new List <RoundRobin> () ;
    // or whatever your custom object name put instead of Vehicle__c
    
    for (Case cs = Trigger.new) {
        
        
        // here is where you check if opportunity that is being inserted
        //meets the criteria
        if (cs.Owner == "Support Queue"); {  
        
        RoundRobin RR = new RoundRobin (); //instantiate the object to put values for future record
        
    
        }//end if
        
    }//end for cs
    
    //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.
    
    
}
Koustubh KulkarniKoustubh Kulkarni
Hello,
I am new to salesforce. I have one junction object called allocation__c which is junction between contact and project__c. Allocation has various fields. after selecting time period(1 week,2 week,1 month,2 months etc.) i want to generate multiple records with same field values but each record for only one week.i.e. if i select 1 month then there should be four records with other parameters remaining same but just change in start and end date. how can we do that??
Ravi Mishra 58Ravi Mishra 58
Hi,

Can anyone let me know what is the issue in below trigger. Requirement is such that if on Student__c object if I Update the Name field then it should create a new record everytime on Backup_Student__c.  On debug log I checked each and everything and the flow seem to be working fine but new record on the Backup_Student__c is not able to create even a single record there.
Here below is the code :-
trigger createBackup on Student__c (After Update) {
    
    if(Trigger.isUpdate){
        for(Integer i = 0; i<trigger.new.size(); i++){
            if(trigger.new[i].name != trigger.old[i].name){
                Backup_Student__c backStu = new Backup_Student__c(Name='Test',Address__c='Address Test',Fee__c=100,Gender__c='Male');
                insert backStu;
            }
            
        }
    }
}

 
Sarah PinnsSarah Pinns
Hi! Could anyone share the Unit Test used for this trigger?  I built something similar but I'm struggling to get code coverage to deploy it into production.  Thanks!