+ Start a Discussion
Lee_CampbellLee_Campbell 

Trigger for IDs for lookup fields

trigger BPT_CreateProject on Procurement__c (before insert, after update) {
    map< id, Milestone1_Project__c > proj = new map< id, Milestone1_Project__c >( );

    
	
    if(Trigger.isinsert){

    for( Procurement__c proc : trigger.new ) {
               proj.put( proc.id,
            new Milestone1_Project__c(
                        Name = proc.Name,
                        
                        Procurement_Link__c = proc.id
                		//a few other fields are passed fine by the code
                		)
            );
    
    insert proj.values();
}

 Hi folks,

 

I was wondering if you could help...

 

In the trigger above, I'm trying to create a new record in a custom object that contains much of the information from another custom object when that is created. So... I create a "Procurement__c" record, and the trigger automatically creates a new "Milestone1_Project__c" record. In this Milestone1_Project__c record, I want a lookup automatically populated with the ID of the Procurement__c record upon creation, among other fields. The other fields work fine when using a trigger like the one above, but this passing of the ID isn't working - the field is blank in the Milestone1_Project__c record.

 

Any ideas as to what I'm doing wrong here?

 

Many thanks,

Lee

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

Inserted records don't have ids in before insert triggers - you probably want to change the trigger to an after insert.

All Answers

bob_buzzardbob_buzzard

Inserted records don't have ids in before insert triggers - you probably want to change the trigger to an after insert.

This was selected as the best answer
Lee_CampbellLee_Campbell

Excellent, thanks.

 

I have a field reference in the other direction as well... as in, my new Procurement record needs to contain a lookup ID to the newly created Milestone1 etc record. I'll just create a second trigger that maps in this direction upon creation of the Milestone1 record. Problem solved.

 

Thanks very much for your help.

bob_buzzardbob_buzzard

You shouldn't need to do that.  Once the insert statements have completed, the records will have their ids populated.  You can than use the ids in your procurement records and update those.

Lee_CampbellLee_Campbell
Yes... of course! Still recovering from "festive brain". Thanks again.